问:
How to give column names after one-hot encoding with sklearn?
Here is my question, I hope someone can help me to figure it out..

To explain, there are more than 10 categorical columns in my data set and each of them has 200-300 categories. I want to convert them into binary values. For that I used first label encoder to convert string categories into numbers. The Label Encoder code and the output is shown below.

After Label Encoder, I used One Hot Encoder From scikit-learn again and it is worked. BUT THE PROBLEM IS, I need column names after one hot encoder. For example, column A with categorical values before encoding. A = [1,2,3,4,..]

It should be like that after encoding,

A-1, A-2, A-3

Anyone know how to assign column names to (old column names -value name or number) after one hot encoding. Here is my one hot encoding and it's output;

I need columns with name because I trained an ANN, but every time data comes up I cannot convert all past data again and again. So, I want to add just new ones every time. Thank anyway..

答:
You can get the column names using  .get_feature_names() attribute.

```<code>>>> ohenc.get_feature_names()
>>> x_cat_df.columns = ohenc.get_feature_names()
</code>```

Detailed example is here.

Update

from Version  1.0, use get_feature_names_out

Body:
You can get the column names using  .get_feature_names() attribute.

>>> ohenc.get_feature_names()
>>> x_cat_df.columns = ohenc.get_feature_names()

Detailed example is here.

Update

from Version  1.0, use get_feature_names_out


来源: stackexchange

问:
Symfony 2.8 -> 3.4 Upgrade IsGranted('IS_AUTHENTICATED_ANONYMOUSLY') Throws Errors
I'm in the process of upgrading Symfony from 2.8 to 3.4 and I have a Authentication Listener.

The constructor of the listener

```<code>  public function __construct(EntityManager $entityManager, SessionInterface $session, Security $security, LoggerInterface $logger, Redis $redis, $secret)
    {
        $this->entityManager    = $entityManager;
        $this->session          = $session;
        $this->security         = $security;
        $this->logger           = $logger;
        $this->redis            = $redis;
        $this->secret           = $secret;
    }
</code>```

On Request Function which is calling in listener

```<code>       public function onRequest(GetResponseEvent $event)
        {

        //Validate token

        //Get Authorization Header
        $headers = $event->getRequest()->headers;
        $authHeader = $headers->get('Authorization');

        //Check if Header value starts with 'Bearer'
        if($this->startsWith($authHeader, self::$BEARER_HEADER)) {

                // Allow request to be processed by controllers
               //token handler

        } else {

            $securityContext = $this->security;
            if ($securityContext->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
                return;
            } else {
                throw new SessionTimeoutException();
            }

        }
    }
</code>```

Service.yml

```<code>app.token_listener:
    class: Insead\MIMBundle\Listener\AuthTokenListener
    arguments: ["@doctrine.orm.entity_manager", "@session", "@security.helper", "@logger", "@redis.authtoken", "%secret%"]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onRequest, priority: 0 }
</code>```

ACL list entry  - security.php

```<code>  'access_control' => array(
       array('path' => '^/api/(.*?)/login', 'role'=>'IS_AUTHENTICATED_ANONYMOUSLY'),
    )
</code>```

im trying to access login route with username and password but i get following error

```<code>GENERAL EXCEPTION: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. in

/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authorization/AuthorizationChecker.php line 55
Exception caught by Listener::
[
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Security.php",
    "line": 65,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationChecker",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY",
      null
    ]
  },
  {
    "file": "/var/www/src/Insead/MIMBundle/Listener/AuthTokenListener.php",
    "line": 135,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Security",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY"
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 212,
    "function": "onRequest",
    "class": "Insead\\MIMBundle\\Listener\\AuthTokenListener",
    "type": "->",
    "args": [
      null,
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 44,
    "function": "doDispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      [
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ],
        [
          null,
          "onController"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "configure"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ]
      ],
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 127,
    "function": "dispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 68,
    "function": "handleRaw",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php",
    "line": 200,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1,
      true
    ]
  },
  {
    "file": "/var/www/web/app.php",
    "line": 29,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\Kernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      }
    ]
  }
]
</code>```

I have spend days on this and i still couldn't figure it out to fix it.

Im sorry if this is already answered question i tried to search and i tried things which were mentioned in various posts and it didn't resolve it. im new to symfony too.

Full Security.php

https://www.codepile.net/pile/7O1LJkpv

AuthTokenListner.php

https://www.codepile.net/pile/Xv1ZMlAP

答:
I believe it's the securitycontext which has been deprecated / removed. isGranted needs to be called on the authorization checker

```<code>return $this->get('security.authorization_checker');
</code>```

You  need the 'security.authorization_checker' service.

You then call isGranted on the authorization_checker service.

```<code>// get the service from the container or pass it in via injection
$authChecker = $this->get('security.authorization_checker');
if ($authChecker->isGranted('IS...')) { ... }
</code>```

I used rector for easier migration. I would highly recommend https://github.com/rectorphp/rector for smooth migration. I can guarantee you will save lots of time by using this tool.

https://www.tomasvotruba.cz/blog/2019/02/28/how-to-upgrade-symfony-2-8-to-3-4/

ContentLicense: CC BY-SA 4.0

Body:
I'm in the process of upgrading Symfony from 2.8 to 3.4 and I have a Authentication Listener.

The constructor of the listener

  public function __construct(EntityManager $entityManager, SessionInterface $session, Security $security, LoggerInterface $logger, Redis $redis, $secret)
    {
        $this->entityManager    = $entityManager;
        $this->session          = $session;
        $this->security         = $security;
        $this->logger           = $logger;
        $this->redis            = $redis;
        $this->secret           = $secret;
    }

On Request Function which is calling in listener

       public function onRequest(GetResponseEvent $event)
        {

        //Validate token

        //Get Authorization Header
        $headers = $event->getRequest()->headers;
        $authHeader = $headers->get('Authorization');

        //Check if Header value starts with 'Bearer'
        if($this->startsWith($authHeader, self::$BEARER_HEADER)) {

                // Allow request to be processed by controllers
               //token handler

        } else {

            $securityContext = $this->security;
            if ($securityContext->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
                return;
            } else {
                throw new SessionTimeoutException();
            }

        }
    }

Service.yml

app.token_listener:
    class: Insead\MIMBundle\Listener\AuthTokenListener
    arguments: ["@doctrine.orm.entity_manager", "@session", "@security.helper", "@logger", "@redis.authtoken", "%secret%"]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onRequest, priority: 0 }

ACL list entry  - security.php

  'access_control' => array(
       array('path' => '^/api/(.*?)/login', 'role'=>'IS_AUTHENTICATED_ANONYMOUSLY'),
    )

im trying to access login route with username and password but i get following error

GENERAL EXCEPTION: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. in

/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authorization/AuthorizationChecker.php line 55
Exception caught by Listener::
[
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Security.php",
    "line": 65,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationChecker",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY",
      null
    ]
  },
  {
    "file": "/var/www/src/Insead/MIMBundle/Listener/AuthTokenListener.php",
    "line": 135,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Security",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY"
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 212,
    "function": "onRequest",
    "class": "Insead\\MIMBundle\\Listener\\AuthTokenListener",
    "type": "->",
    "args": [
      null,
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 44,
    "function": "doDispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      [
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ],
        [
          null,
          "onController"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "configure"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ]
      ],
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 127,
    "function": "dispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 68,
    "function": "handleRaw",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php",
    "line": 200,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1,
      true
    ]
  },
  {
    "file": "/var/www/web/app.php",
    "line": 29,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\Kernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      }
    ]
  }
]

I have spend days on this and i still couldn't figure it out to fix it.

Im sorry if this is already answered question i tried to search and i tried things which were mentioned in various posts and it didn't resolve it. im new to symfony too.

Full Security.php

https://www.codepile.net/pile/7O1LJkpv

AuthTokenListner.php

https://www.codepile.net/pile/Xv1ZMlAP

Body:
I believe it's the securitycontext which has been deprecated / removed. isGranted needs to be called on the authorization checker

return $this->get('security.authorization_checker');

You  need the 'security.authorization_checker' service.

You then call isGranted on the authorization_checker service.

// get the service from the container or pass it in via injection
$authChecker = $this->get('security.authorization_checker');
if ($authChecker->isGranted('IS...')) { ... }

I used rector for easier migration. I would highly recommend https://github.com/rectorphp/rector for smooth migration. I can guarantee you will save lots of time by using this tool.

https://www.tomasvotruba.cz/blog/2019/02/28/how-to-upgrade-symfony-2-8-to-3-4/


问:
PowerPoint automatically fill shapes
My PowerPoint has a timeline which i created my self with "SmartArt" and Shapes. Now i want that all the shapes in this timeline will fill automatically with dates if i edit the first date.

In the picture you can see my timeline.

I am totally new to PowerPoint VBA so i do not even know how to call this macro.

I would write the makro like this:

```<code>Sub Fill_Shapes()
    Dim StartDate As Date
    Dim myShape As Object

    Set myShape = ActiveSlide.Shapes(1)
    StartDate = myShape.Text

    For i = 2 To 14
        Set myShape = ActiveSlide.Shapes(i)
        With Application.Presentations(1).Slides(3).Shapes(i).TextFrame.TextRange
            .Text = StartDate  + 15
        End With
        StartDate = myShape.Text
    Next
End If
</code>```

So my two problems are, how can i call the macro if i fill a date to the shape 1 (left from the red arrow) and will my macro even work the way i write it?

答:
I think you are confusing Shapes with the individual elements (nodes) of SmartArt.

Smart Art is a effectively a single shape with its own inbuilt elements.  Therefore, with i being your looper you should be looking at

```<code>With Application.Presentations(1).Slides(3).Shapes(99).SmartArt.AllNodes.Item(i).TextFrame2.TextRange
</code>```

Where 99 is the number of your shape (although you are better to refer to it by name).

Title: PowerPoint automatically fill shapes

Body:
My PowerPoint has a timeline which i created my self with "SmartArt" and Shapes. Now i want that all the shapes in this timeline will fill automatically with dates if i edit the first date.

In the picture you can see my timeline.

I am totally new to PowerPoint VBA so i do not even know how to call this macro.

I would write the makro like this:

Sub Fill_Shapes()
    Dim StartDate As Date
    Dim myShape As Object

    Set myShape = ActiveSlide.Shapes(1)
    StartDate = myShape.Text

    For i = 2 To 14
        Set myShape = ActiveSlide.Shapes(i)
        With Application.Presentations(1).Slides(3).Shapes(i).TextFrame.TextRange
            .Text = StartDate  + 15
        End With
        StartDate = myShape.Text
    Next
End If

So my two problems are, how can i call the macro if i fill a date to the shape 1 (left from the red arrow) and will my macro even work the way i write it?

Body:
I think you are confusing Shapes with the individual elements (nodes) of SmartArt.

Smart Art is a effectively a single shape with its own inbuilt elements.  Therefore, with i being your looper you should be looking at

With Application.Presentations(1).Slides(3).Shapes(99).SmartArt.AllNodes.Item(i).TextFrame2.TextRange

Where 99 is the number of your shape (although you are better to refer to it by name).


问:
Can I run minikube without any RBAC?
Can we run minikube without RBAC. Please see the attached screenshot. Looks like RBAC is enabled by default.

答:
Since minikube v0.26.0 the default bootstrapper is kubeadm - which enables RBAC by default.

For the previous versions, you have to explicitly enable it by adding a flag

```<code>-extra-config=apiserver.Authorization.Mode=RBAC
</code>```

Otherwise it will not be enabled

To disable RBAC in latest versions of the minikube, set following flag

```<code>--extra-config=apiserver.authorization-mode=AlwaysAllow
</code>```

If it won't work, try workaround suggested here

Title: Can I run minikube without any RBAC?

Body:
Since minikube v0.26.0 the default bootstrapper is kubeadm - which enables RBAC by default.

For the previous versions, you have to explicitly enable it by adding a flag

-extra-config=apiserver.Authorization.Mode=RBAC

Otherwise it will not be enabled

To disable RBAC in latest versions of the minikube, set following flag

--extra-config=apiserver.authorization-mode=AlwaysAllow

If it won't work, try workaround suggested here


问:
Not able to parse JSON file in JavaScript
I am using JavaScript to Parse the JSON file. But I am not able understand the error I am getting. Could anybody please help me on this topic.

**My Code:
Html file:

```<code><title>JSON Parser</title>
<script type="text/javascript">
    function webGLStart() {
       var request = new XMLHttpRequest();
       request.open("GET","test.json");
       var my_JSON_object = JSON.parse(request.responseText);
     alert (my_JSON_object.result[0]);
    }

</script>
</head>
<body onload="webGLStart();">
</body>
</html>
</code>```

test.json File:

```<code>{"result": [0,1,2,3,4] }
</code>```

alert in above code does not show anything on the webpage.

答:
Ajax is asynchronous. You are trying to read the response before it has arrived from the server. Oh, worse than that. You are opening the request but never actually sending it.

You need to use an event handler onreadystate change to run the code once the response has arrived, and you need to send the request to the server before you can get a response. There is a decent guide to using XHR here.

ContentLicense: CC BY-SA 3.0

Body:
I am using JavaScript to Parse the JSON file. But I am not able understand the error I am getting. Could anybody please help me on this topic.

**My Code:
Html file:

<title>JSON Parser</title>

test.json File:

{"result": [0,1,2,3,4] }

alert in above code does not show anything on the webpage.


问:
Returning first_name and last_name in a dropdown
I have a dropdown of usernames, but I would like instead first_name + Last_name from the user model. I have been trying to return these in the model in various ways, any idea where I've gone wrong?

```<code>def __str__(self):
    # return self.assigned_to.first_name
    # return str(self.firstname)+ '-' +str(self.lastname)
    # return u'%s %s' % (assigned_to.first_name, self.last_name)
    # return str(self.user.first_name)
    # return str(self.location_name)+ '.' +str(self.location_sub_name)
</code>```

In my model:

```<code>assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='assigned_to', on_delete = models.PROTECT, related_name='assigned')
</code>```

In my htmlform:

```<code><div class="col col-md-4" style="color:white;">{{ form.assigned_to|add_class:"col-md-12"|append_attr:"placeholder:To"}}</div>
</code>```

答:
The first_name and last_name are attributes of the User model [Django-doc], given of course that you use that model, or a model that has a first_name and last_name attribute. You obtain these through self.assigned_to.first_name and self.assigned_to.last_name:

```<code>class MyModel(models.Model):
    assigned_to = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        db_column='assigned_to',
        on_delete=models.PROTECT,
        related_name='assigned'
    )

    def __str__(self):
        return '{} {}'.format(
            self.assigned_to.first_name,
            self.assigned_to.last_name
        )</code>```

As for your Form, you should specify the attrs into the form class itself.

Body:
I have a dropdown of usernames, but I would like instead first_name + Last_name from the user model. I have been trying to return these in the model in various ways, any idea where I've gone wrong?

def __str__(self):
    # return self.assigned_to.first_name
    # return str(self.firstname)+ '-' +str(self.lastname)
    # return u'%s %s' % (assigned_to.first_name, self.last_name)
    # return str(self.user.first_name)
    # return str(self.location_name)+ '.' +str(self.location_sub_name)

In my model:

assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='assigned_to', on_delete = models.PROTECT, related_name='assigned')

In my htmlform:

{{ form.assigned_to|add_class:"col-md-12"|append_attr:"placeholder:To"}}

Body:
The first_name and last_name are attributes of the User model [Django-doc], given of course that you use that model, or a model that has a first_name and last_name attribute. You obtain these through self.assigned_to.first_name and self.assigned_to.last_name:

class MyModel(models.Model):
    assigned_to = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        db_column='assigned_to',
        on_delete=models.PROTECT,
        related_name='assigned'
    )

    def __str__(self):
        return '{} {}'.format(
            self.assigned_to.first_name,
            self.assigned_to.last_name
        )

As for your Form, you should specify the attrs into the form class itself.


问:
how can I specify multiple "init_command"s in Django's setup file
I have the following setup for my connections to a MySQL database in Django.

```<code>'default': {
    'NAME' : MYSQL_DB_NAME,
    #'ENGINE' : 'mysql',
    'ENGINE' : 'django.db.backends.mysql',
    'USER' : 'ccurvey',
    'PASSWORD' : MYSQL_PASSWORD,
    'HOST' : MYSQL_HOST,
    'PORT' : '',
    'OPTIONS' : {
        'init_command' : 'set storage_engine=INNODB',
        },
    },
</code>```

so far, so good.

What's the incantation if I want to add another "set" command to my "init_command"

```<code>        'init_command' : ('set storage_engine=INNODB',
                           'set transaction isolation level read committed'),
</code>```

gives me "connect() argument must be string, not tuple"

```<code>        'init_command' : ('set storage_engine=INNODB; set transaction isolation level read committed;'),
</code>```

gives me

```<code>_mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
</code>```

答:
@ChrisCurvey's solution is OKay for me.

ENV: Python3.7.3 + Django2.2.1

```<code>'OPTIONS': {
    'init_command': 'SET default_storage_engine=INNODB, sql_mode="STRICT_TRANS_TABLES" ',
    'charset': 'utf8mb4',
},
</code>```

Body:
I have the following setup for my connections to a MySQL database in Django.

'default': {
    'NAME' : MYSQL_DB_NAME,
    #'ENGINE' : 'mysql',
    'ENGINE' : 'django.db.backends.mysql',
    'USER' : 'ccurvey',
    'PASSWORD' : MYSQL_PASSWORD,
    'HOST' : MYSQL_HOST,
    'PORT' : '',
    'OPTIONS' : {
        'init_command' : 'set storage_engine=INNODB',
        },
    },

so far, so good.

What's the incantation if I want to add another "set" command to my "init_command"

        'init_command' : ('set storage_engine=INNODB',
                           'set transaction isolation level read committed'),

gives me "connect() argument must be string, not tuple"

        'init_command' : ('set storage_engine=INNODB; set transaction isolation level read committed;'),

gives me

_mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")

Body:
@ChrisCurvey's solution is OKay for me.

ENV: Python3.7.3 + Django2.2.1

'OPTIONS': {
    'init_command': 'SET default_storage_engine=INNODB, sql_mode="STRICT_TRANS_TABLES" ',
    'charset': 'utf8mb4',
},


问:
Encountering IllegalArgumentException in Jboss EAP
I'm miograting an app in our server, from Websphere to JBoss EAP7.
The app is working fine in the Webspehere server but when we migrate in in JBoss, we are encountering an exception upon logging in the app.

```<code>java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException
</code>```

Here is the stacktrace of the error.

```<code>2019-05-28 17:17:38,161 ERROR [stderr] (default task-7) java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at org.wildfly.clustering.web.infinispan.session.coar  se.CoarseSessionAttributes.setAttribute(CoarseSessionAttributes.java:63)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at org.wildfly.clustering.web.undertow.session.Distri  butableSession.setAttribute(DistributableSession.java:147)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at io.undertow.servlet.spec.HttpSessionImpl.setAttrib  ute(HttpSessionImpl.java:169)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.t  oHomePage(LoginProcessor.java:803)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.p  erformTask(LoginProcessor.java:327)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.e  xecute(LoginProcessor.java:146)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.ActionListener.e  xecute(ActionListener.java:41)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.performT  ask(CommonServlet.java:289)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.doPost(C  ommonServlet.java:82)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:707)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:790)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletHandler.handle  Request(ServletHandler.java:85)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletSecur  ityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletDispatchingHan  dler.handleRequest(ServletDispatchingHandler.java:36)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.SecurityCo  ntextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.SSLInformati  onAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletAuthe  nticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractConfidential  ityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletConfi  dentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AuthenticationMechan  ismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.CachedAuthen  ticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.NotificationReceiver  Handler.handleRequest(NotificationReceiverHandler.java:50)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractSecurityCont  extAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.jacc.JACCC  ontextIdHandler.handleRequest(JACCContextIdHandler.java:61)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .handleFirstRequest(ServletInitialHandler.java:285)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .dispatchRequest(ServletInitialHandler.java:264)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .access$000(ServletInitialHandler.java:81)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  $1.handleRequest(ServletInitialHandler.java:175)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.server.Connectors.executeRootHandler(C  onnectors.java:202)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.server.HttpServerExchange$1.run(HttpSe  rverExchange.java:792)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at java.util.concurrent.ThreadPoolExecutor.runWorker(  ThreadPoolExecutor.java:1149)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at java.util.concurrent.ThreadPoolExecutor$Worker.run  (ThreadPoolExecutor.java:624)
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7)         at java.lang.Thread.run(Thread.java:748)
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) Caused by: org.infinispan.commons.marshall.NotSerializableExc  eption: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) java.lang.Exception: org.infinispan.commons.marshall.NotSeria  lizableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.t  oHomePage(LoginProcessor.java:809)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.p  erformTask(LoginProcessor.java:327)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.e  xecute(LoginProcessor.java:146)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.ActionListener.e  xecute(ActionListener.java:41)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.performT  ask(CommonServlet.java:289)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.doPost(C  ommonServlet.java:82)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:707)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:790)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletHandler.handle  Request(ServletHandler.java:85)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletSecur  ityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletDispatchingHan  dler.handleRequest(ServletDispatchingHandler.java:36)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.SecurityCo  ntextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.SSLInformati  onAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletAuthe  nticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractConfidential  ityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletConfi  dentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AuthenticationMechan  ismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.CachedAuthen  ticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.NotificationReceiver  Handler.handleRequest(NotificationReceiverHandler.java:50)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractSecurityCont  extAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.jacc.JACCC  ontextIdHandler.handleRequest(JACCContextIdHandler.java:61)

</code>```

Any inputs would be appreciated thanks!

答:
JVM says this is an issue:

```<code>2019-05-28 17:17:38,161 ERROR [stderr] (default task-7) java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) Caused by: org.infinispan.commons.marshall.NotSerializableExc  eption: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) java.lang.Exception: org.infinispan.commons.marshall.NotSeria  lizableException: ph.com.crm.common.admin.ListLovListVO
</code>```

Is that dependency from your project?  Is it part of your pom.xml?  Or was it carried over from WebSphere, assuming that it'd be part of JBOSS?

Body:
I'm miograting an app in our server, from Websphere to JBoss EAP7.
The app is working fine in the Webspehere server but when we migrate in in JBoss, we are encountering an exception upon logging in the app.

java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException

Here is the stacktrace of the error.

2019-05-28 17:17:38,161 ERROR [stderr] (default task-7) java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at org.wildfly.clustering.web.infinispan.session.coar  se.CoarseSessionAttributes.setAttribute(CoarseSessionAttributes.java:63)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at org.wildfly.clustering.web.undertow.session.Distri  butableSession.setAttribute(DistributableSession.java:147)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at io.undertow.servlet.spec.HttpSessionImpl.setAttrib  ute(HttpSessionImpl.java:169)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.t  oHomePage(LoginProcessor.java:803)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.p  erformTask(LoginProcessor.java:327)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.e  xecute(LoginProcessor.java:146)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.ActionListener.e  xecute(ActionListener.java:41)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.performT  ask(CommonServlet.java:289)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.doPost(C  ommonServlet.java:82)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:707)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:790)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletHandler.handle  Request(ServletHandler.java:85)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletSecur  ityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletDispatchingHan  dler.handleRequest(ServletDispatchingHandler.java:36)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.SecurityCo  ntextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.SSLInformati  onAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletAuthe  nticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractConfidential  ityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletConfi  dentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AuthenticationMechan  ismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.CachedAuthen  ticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.NotificationReceiver  Handler.handleRequest(NotificationReceiverHandler.java:50)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractSecurityCont  extAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.jacc.JACCC  ontextIdHandler.handleRequest(JACCContextIdHandler.java:61)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .handleFirstRequest(ServletInitialHandler.java:285)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .dispatchRequest(ServletInitialHandler.java:264)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .access$000(ServletInitialHandler.java:81)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  $1.handleRequest(ServletInitialHandler.java:175)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.server.Connectors.executeRootHandler(C  onnectors.java:202)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.server.HttpServerExchange$1.run(HttpSe  rverExchange.java:792)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at java.util.concurrent.ThreadPoolExecutor.runWorker(  ThreadPoolExecutor.java:1149)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at java.util.concurrent.ThreadPoolExecutor$Worker.run  (ThreadPoolExecutor.java:624)
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7)         at java.lang.Thread.run(Thread.java:748)
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) Caused by: org.infinispan.commons.marshall.NotSerializableExc  eption: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) java.lang.Exception: org.infinispan.commons.marshall.NotSeria  lizableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.t  oHomePage(LoginProcessor.java:809)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.p  erformTask(LoginProcessor.java:327)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.e  xecute(LoginProcessor.java:146)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.ActionListener.e  xecute(ActionListener.java:41)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.performT  ask(CommonServlet.java:289)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.doPost(C  ommonServlet.java:82)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:707)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:790)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletHandler.handle  Request(ServletHandler.java:85)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletSecur  ityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletDispatchingHan  dler.handleRequest(ServletDispatchingHandler.java:36)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.SecurityCo  ntextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.SSLInformati  onAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletAuthe  nticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractConfidential  ityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletConfi  dentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AuthenticationMechan  ismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.CachedAuthen  ticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.NotificationReceiver  Handler.handleRequest(NotificationReceiverHandler.java:50)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractSecurityCont  extAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.jacc.JACCC  ontextIdHandler.handleRequest(JACCContextIdHandler.java:61)

Any inputs would be appreciated thanks!

Body:
JVM says this is an issue:

2019-05-28 17:17:38,161 ERROR [stderr] (default task-7) java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) Caused by: org.infinispan.commons.marshall.NotSerializableExc  eption: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) java.lang.Exception: org.infinispan.commons.marshall.NotSeria  lizableException: ph.com.crm.common.admin.ListLovListVO

Is that dependency from your project?  Is it part of your pom.xml?  Or was it carried over from WebSphere, assuming that it'd be part of JBOSS?


问:
Should i update reducers state for specific component or manage in component state?
In my project i normally get data from reducers and pass data to component, in that component if data is to be updated e.g

obj :{ age:20, name: 'hassan' }

for any update action than i create copy of this object to my own state in constructor as

```<code>this.state {
    obj : this.props.obj
}
</code>```

then utilize copied obj and send to service for update actions to server side etc.

but i never update reducers object instead always create component own state.

I am new to react please guide me should i update reducers object and further utilize it instead to create own state for component and if i should update reducers object it effects permormance or currently pattern i am following is better or not ?

答:
The concept of redux comes down to maintaining a global state that can be accessed by any component.

The usage of the store differs based on the variable you are storing. It is recommended to store only the values which are being used by other components .If that's not the case you can maintain the state in indvidual react components.

redux store vs react state this tutorial gives a handfull experience to choose wisely

Body:
In my project i normally get data from reducers and pass data to component, in that component if data is to be updated e.g

obj :{ age:20, name: 'hassan' }

for any update action than i create copy of this object to my own state in constructor as

this.state {
    obj : this.props.obj
}

then utilize copied obj and send to service for update actions to server side etc.

but i never update reducers object instead always create component own state.

I am new to react please guide me should i update reducers object and further utilize it instead to create own state for component and if i should update reducers object it effects permormance or currently pattern i am following is better or not ?


问:
Convert string into MongoDB BsonDocument
I have a long string in JSON format, and I want to convert it into a BSONDocument for insertion into a MongoDB database.  How do I do the conversion?  I'm using the official C# driver.</p>

答:
The answer is:</p>

```<code>string json = "{ 'foo' : 'bar' }";
MongoDB.Bson.BsonDocument document
    = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);
</code>```

Body:
The answer is:

string json = "{ 'foo' : 'bar' }";
MongoDB.Bson.BsonDocument document
    = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);


问:
Java best practices static final map values
I have a utility class which contains a static final map with some values. I need to access to this map in another class. Should I just declare the map as public, or should I write a getter inside the utility class, and therefore let the map be private?

Both ways work, but what are the best practices?

```<code>public MyUtilityClass {
  public static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

}

public MyAnotherClass {

  public void someMethod() {
    //accessing the map directly
    MAX_LENGTHS.get("title")
  }

}
</code>```

Or

```<code>public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static final getMaxLengthMap() {return MAX_LENGTHS;}
}

public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLengthMap().get("title")
  }
}
</code>```

Well, actually the keys are enum values.
Something like :

```<code>private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      MyEnumClass.TITLE, 256,
      MyEnumClass.TEXT, 512);
</code>```

答:
You are using ImmutableMap from guava project; thus a true immutable Map.

Making it public would not hurt anyone - as no one can really alter that Map in any way.

Body:
I have a utility class which contains a static final map with some values. I need to access to this map in another class. Should I just declare the map as public, or should I write a getter inside the utility class, and therefore let the map be private?

Both ways work, but what are the best practices?

public MyUtilityClass {
  public static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

}

public MyAnotherClass {

  public void someMethod() {
    //accessing the map directly
    MAX_LENGTHS.get("title")
  }

}

Or

public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static final getMaxLengthMap() {return MAX_LENGTHS;}
}

public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLengthMap().get("title")
  }
}

Well, actually the keys are enum values.
Something like :

private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      MyEnumClass.TITLE, 256,
      MyEnumClass.TEXT, 512);


问:
Create Virtual Environment using Python Documentation
I am very new at command line usage. I am using python 3.7.2, Bash and VSCode Integrated Terminal. I am trying to create a virtual environment using venv and following python documentation:

https://docs.python.org/3/tutorial/venv.html#creating-virtual-environments

The command to use is this one:

```<code>$ python3 -m venv test-env
</code>```

and I get:

```<code>bash: python3: command not found
</code>```

Later I have found a similar answer in an stackoverflow post:

How to create and activate virtual environment in windows 10 using bash command

And I use the command:

```<code>py -m virtualenv test-env
</code>```

and I get this:

```<code>No module named virtualenv
</code>```

I am very new using the command line so i don´t really know what is going on and how to work it around.

答:
Hi i can see that you are using two different tools to create your environment.
Those are "venv" and "virtualenv".
Venv is a library that already comes with your python installation.
Virtualenv is an external one.
I had the same problem before and the solution is very simple.
I recommend you to stick with venv because it works pretty ok and you don´t need to do extra job installing external libraries.
So for solving your problem the Bash Shell is telling you that the command Python3 has not been found.
So try instead just:
python -m venv test-env

Sometimes Python documentation is not accurate enough and I know when you start using commands, accuracy in the sintax is extremely important.

Body:
I am very new at command line usage. I am using python 3.7.2, Bash and VSCode Integrated Terminal. I am trying to create a virtual environment using venv and following python documentation:

https://docs.python.org/3/tutorial/venv.html#creating-virtual-environments

The command to use is this one:

$ python3 -m venv test-env

and I get:

bash: python3: command not found

Later I have found a similar answer in an stackoverflow post:

How to create and activate virtual environment in windows 10 using bash command

And I use the command:

py -m virtualenv test-env

and I get this:

No module named virtualenv

I am very new using the command line so i don´t really know what is going on and how to work it around.


问:
MS Analysis Services OLAP API for Python
I am looking for a way to connect to a MS Analysis Services OLAP cube, run MDX queries, and pull the results into Python. In other words, exactly what Excel does. Is there a solution in Python that would let me do that?

Someone with a similar question going pointed to Django's ORM. As much as I like the framework, this is not what I am looking for. I am also not looking for a way to pull rows and aggregate them -- that's what Analysis Services is for in the first place.

Ideas? Thanks.

答:
You can easily connect and access OLAP cubes with the help of python package xmla. xmla plays a vital role in communicating with OLAP and performs all functions with the cubes.

Install xmla package either by

```<code>python -m pip install xmla --user
</code>```

or

```<code>python -m venv xmlaenv
# python -m venv --without-pip xmlenv - use if the above commands throws error
cd xmlaenv
source bin/activate
git clone https://github.com/may-day/olap
cd olap/xmla
# optional if you have it already
pip install pipenv
pipenv install -dev
python setup.py develop
</code>```

After installation, Connect to OLAP XMLA Cubes using location, username and password parameters.

```<code>import olap.xmla.xmla as xmla
provider = xmla.XMLAProvider()
connect = provider.connect(location='http://localhost/OLAP/msmdpump.dll',
 username = 'test', password = 'test')
source = connect.getOLAPSource()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can easily connect and access OLAP cubes with the help of python package xmla. xmla plays a vital role in communicating with OLAP and performs all functions with the cubes.

Install xmla package either by

python -m pip install xmla --user

or

python -m venv xmlaenv
# python -m venv --without-pip xmlenv - use if the above commands throws error
cd xmlaenv
source bin/activate
git clone https://github.com/may-day/olap
cd olap/xmla
# optional if you have it already
pip install pipenv
pipenv install -dev
python setup.py develop

After installation, Connect to OLAP XMLA Cubes using location, username and password parameters.

import olap.xmla.xmla as xmla
provider = xmla.XMLAProvider()
connect = provider.connect(location='http://localhost/OLAP/msmdpump.dll',
 username = 'test', password = 'test')
source = connect.getOLAPSource()


答:
The getter does not add anything - I would just keep it public.

What may make sense is to have a method that returns the value directly:

```<code>public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static final getMaxLength(String item) {return MAX_LENGTHS.get(item);}
}

public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLength("title");
  }
}
</code>```

This also allows you to easily modify the underlying implementation later on. For example you could return a default value for items not in the map etc.

Title: Java best practices static final map values

Body:
The getter does not add anything - I would just keep it public.

What may make sense is to have a method that returns the value directly:

public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static final getMaxLength(String item) {return MAX_LENGTHS.get(item);}
}

public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLength("title");
  }
}

This also allows you to easily modify the underlying implementation later on. For example you could return a default value for items not in the map etc.


问:
Not able to Resolve NavigationContext in WPF xaml page have referenced System.Windows.Navigation
I have created a WPF application and passing data from one page to another using navigation service but when I am trying to access navigation context to resolve query string, it not getting resolved I have already referenced System.Windows.Navigation

Sending IP from Home Page to Page1

```<code>  private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("Page1.xaml?
   IP="+txtIP.Text, UriKind.RelativeOrAbsolute));
        }
</code>```

On Page1 Loaded event not able to resolve Navigation Context

```<code> private void Page1_Loaded(object sender, RoutedEventArgs e)
   {
            string val;
            if (this.NavigationContext.QueryString.TryGetValue("IP", out val))
            {
                MessageBox.Show(val, "Information", MessageBoxButton.OK);
            }
        }
</code>```

答:
NavigationContext is a Silverlight type. If you add a reference to System.Web, you could use the HttpUtility to extract the parameters from the NavigationService's CurrentSource property:

```<code>private void Page1_Loaded(object sender, RoutedEventArgs e)
{
    string uri = this.NavigationService.CurrentSource.ToString();
    string querystring = uri.ToString().Substring(uri.IndexOf('?'));
    System.Collections.Specialized.NameValueCollection parameters = System.Web.HttpUtility.ParseQueryString(querystring);

    string val = parameters["IP"];
    if (!string.IsNullOrEmpty(val))
    {
        MessageBox.Show(val, "Information", MessageBoxButton.OK);
    }
}
</code>```

Body:
I have created a WPF application and passing data from one page to another using navigation service but when I am trying to access navigation context to resolve query string, it not getting resolved I have already referenced System.Windows.Navigation

Sending IP from Home Page to Page1

  private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("Page1.xaml?
   IP="+txtIP.Text, UriKind.RelativeOrAbsolute));
        }

On Page1 Loaded event not able to resolve Navigation Context

 private void Page1_Loaded(object sender, RoutedEventArgs e)
   {
            string val;
            if (this.NavigationContext.QueryString.TryGetValue("IP", out val))
            {
                MessageBox.Show(val, "Information", MessageBoxButton.OK);
            }
        }

Body:
NavigationContext is a Silverlight type. If you add a reference to System.Web, you could use the HttpUtility to extract the parameters from the NavigationService's CurrentSource property:

private void Page1_Loaded(object sender, RoutedEventArgs e)
{
    string uri = this.NavigationService.CurrentSource.ToString();
    string querystring = uri.ToString().Substring(uri.IndexOf('?'));
    System.Collections.Specialized.NameValueCollection parameters = System.Web.HttpUtility.ParseQueryString(querystring);

    string val = parameters["IP"];
    if (!string.IsNullOrEmpty(val))
    {
        MessageBox.Show(val, "Information", MessageBoxButton.OK);
    }
}


问:
Assert called with argument of specific type
I want to check in my test if a function is called with an argument of a specific class.

```<code>class Foo:
...
</code>```

I found mock.ANY, but there I cannot pass any class. What is want is:

```<code>test_mock.assert_called_with("expected string", ANY(spec=Foo))
</code>```

答:
You could check by the name of the class by using the class name:</p>

```<code>class MyClass(object):
    def __init__(self, x):
        self.x = x

a = MyClass(3)
print(a.__class__.__name__)
if a.__class__.__name__ == "MyClass":
    ...
</code>```

Body:
I want to check in my test if a function is called with an argument of a specific class.

class Foo:
...

I found mock.ANY, but there I cannot pass any class. What is want is:

test_mock.assert_called_with("expected string", ANY(spec=Foo))

Body:
You could check by the name of the class by using the class name:

class MyClass(object):
    def __init__(self, x):
        self.x = x

a = MyClass(3)
print(a.__class__.__name__)
if a.__class__.__name__ == "MyClass":
    ...


问:
Alert box needs to be closed multiple times
I'm checking the value of a form field and if the value is more than 5 an alert box pops up. This works, but I've noticed that if I fill in the field 1 time, the alert box can be closed normally. If I then enter a new value, also above 5, I need to close the alert box two times, and three times if I would enter a third value. And so on...

I read several related questions on Stackoverflow, but none seemed to be the same issue or related.

window.onload = function() {
  displayField();
};

function displayField() {
  jQuery('#groupnumber').change(function() {
    var amount5 = jQuery('#groupnumber').val();
    if (amount5 > 5) {
      alert('Alert message');
    }
  });
};

//Trigger javascript on leaving field
onblur = "displayField();"
```

So it "keeps score". If I enter a different value the second time and it is still above 5, I would like the alert box to just show once.

Thanks for any help!

答:
The issue is because you call displayField() every time a blur event occurs which in turn adds another change event handler. Therefore when the next change happens all of those handlers are executed.

You can fix this by attaching your event unobtrusively. This way there will only ever be a single event added when the page loads, and it will fire whenever the selected event occurs on the element.

This does work, but has one disadvantage: if one would enter 78, the alert box shows directly after typing the 7, instead of showing when someone is ready with their input. How can that be avoided?

To mitigate that you could 'debounce' the event so that you only show the alert X milliseconds after typing has ended. You can use setTimeout() to do that:

jQuery(function($) {
  var timer;

  $('#groupnumber').on('input', function() {
    clearTimeout(timer);
    timer = setTimeout(function() {
      var amount5 = $('#groupnumber').val();
      if (amount5 > 5) {
        alert('Alert message');
      }
    }, 200);
  }).trigger('input'); // fire the event when the page loads
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="groupnumber" /></code>```

Note the aliasing of $ in the document.ready handler. This means you can still use $ within the block to refer to jQuery, making your code slightly less verbose.

Body:
I'm checking the value of a form field and if the value is more than 5 an alert box pops up. This works, but I've noticed that if I fill in the field 1 time, the alert box can be closed normally. If I then enter a new value, also above 5, I need to close the alert box two times, and three times if I would enter a third value. And so on...

I read several related questions on Stackoverflow, but none seemed to be the same issue or related.

window.onload = function() {
  displayField();
};

function displayField() {
  jQuery('#groupnumber').change(function() {
    var amount5 = jQuery('#groupnumber').val();
    if (amount5 > 5) {
      alert('Alert message');
    }
  });
};

//Trigger javascript on leaving field
onblur = "displayField();"

So it "keeps score". If I enter a different value the second time and it is still above 5, I would like the alert box to just show once.

Thanks for any help!

Body:
The issue is because you call displayField() every time a blur event occurs which in turn adds another change event handler. Therefore when the next change happens all of those handlers are executed.

You can fix this by attaching your event unobtrusively. This way there will only ever be a single event added when the page loads, and it will fire whenever the selected event occurs on the element.

This does work, but has one disadvantage: if one would enter 78, the alert box shows directly after typing the 7, instead of showing when someone is ready with their input. How can that be avoided?

To mitigate that you could 'debounce' the event so that you only show the alert X milliseconds after typing has ended. You can use setTimeout() to do that:

jQuery(function($) {
  var timer;

  $('#groupnumber').on('input', function() {
    clearTimeout(timer);
    timer = setTimeout(function() {
      var amount5 = $('#groupnumber').val();
      if (amount5 > 5) {
        alert('Alert message');
      }
    }, 200);
  }).trigger('input'); // fire the event when the page loads
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="groupnumber" />

Note the aliasing of $ in the document.ready handler. This means you can still use $ within the block to refer to jQuery, making your code slightly less verbose.


问:
How to work with the url of a fileReader object?

Hello! I'am trying to make it work a function called loadDocument, who need a url of the loaded files from the user local computer to work. I'm writing an API to load document from local user computer, and show it on a web reader.

This is my upload button :
  <input type="file" id="input" onchange="module.onLoadSelection();" alt="Browse" name="upload"/>

This is my function without fileReader :

var onLoadSelection = function () {
    var select = document.getElementById('input');
    if (select && select.value) {
        var id= '';
        var url = select.files.item(0).name;
        module.loadDocument(url,id);
    }
};
```

<p>This is my function with fileReader :</p>

<pre class="lang-js prettyprint-override"><code>var loadTest = function (input) {
    var file = document.querySelector('input[type=file]').files[0];
    console.log("file loaded! ->", file); // i can read the obj of my file
    var reader = new FileReader();

    var id = ''; // don't need rightnow
    var url = reader.readAsDataURL(file);
    console.log("url :", url); // show me undefined....
    module.loadDocument(url,id);
}
</code>```

What i am trying is to get the url of the loaded file from user computer to get my function loadDocument working. She need a url parameter to work.

loadDocument is an API function, i assume i can't get the filepath of my user due to security reason.

What do i need to change/update on my loadDocument(); function to work?

Edit : In fact, nothing to change. The correct way to read my file was :
<input type="file" id="input" onchange="module.onLoadSelection(this.files);" alt="Browse" name="upload"/>

var onLoadSelection = function (files) {
    if (files && files.length == 1) {
       var id = '';
       var url = URL.createObjectURL(files[0]);
       module.loadDocument(url,id);
    }
};
```

答:
```<code> function PreviewFiles(input) {
        if (input.files && input.files[0]) {
             var reader = new FileReader();
             reader.onload = function (e) {
             //alert(e.target.result);
                 $('#pclogo').prop('src', e.target.result)
                    .width(200)
                    .height(200);
                    var base64result = e.target.result.split(',')[1];
                $('input[name="logo"]').val(base64result);
            };
            reader.readAsDataURL(input.files[0]);

            }

        }
</code>```

Body:
Hello! I'am trying to make it work a function called loadDocument, who need a url of the loaded files from the user local computer to work. I'm writing an API to load document from local user computer, and show it on a web reader.

This is my upload button :
  <input type="file" id="input" onchange="module.onLoadSelection();" alt="Browse" name="upload"/>

This is my function without fileReader :

var onLoadSelection = function () {
    var select = document.getElementById('input');
    if (select && select.value) {
        var id= '';
        var url = select.files.item(0).name;
        module.loadDocument(url,id);
    }
};

This is my function with fileReader :

var loadTest = function (input) {
    var file = document.querySelector('input[type=file]').files[0];
    console.log("file loaded! ->", file); // i can read the obj of my file
    var reader = new FileReader();

    var id = ''; // don't need rightnow
    var url = reader.readAsDataURL(file);
    console.log("url :", url); // show me undefined....
    module.loadDocument(url,id);
}

What i am trying is to get the url of the loaded file from user computer to get my function loadDocument working. She need a url parameter to work.

loadDocument is an API function, i assume i can't get the filepath of my user due to security reason.

What do i need to change/update on my loadDocument(); function to work?

Edit : In fact, nothing to change. The correct way to read my file was :
<input type="file" id="input" onchange="module.onLoadSelection(this.files);" alt="Browse" name="upload"/>

var onLoadSelection = function (files) {
    if (files && files.length == 1) {
       var id = '';
       var url = URL.createObjectURL(files[0]);
       module.loadDocument(url,id);
    }
};


问:
How to bind ObservableCollection<T> on Datagrid?
I'm David. I don`t know to bind collection to datagrid in XAML for a WPF application.

below are classes.

```<code>class TestSetting(): INotifyChanged
{
   private a
   public double A
   {
      get a;
      set a = value;
      Notify("A");
   }

   private b
   public double B
   {
      get b;
      set b = value;
      Notify("B");
   }

   private c
   public double C
   {
      get c;
      set c = value;
      Notify("C");
   }

}

class TestCollect():ObservableCollection<T> ,INotifyListener
{

}
</code>```

above code is Psedo code.

DataContext has 7 items. So the grid will have 7 columns. Could someone please help me with an example or a code snippet.

答:
I think that what you need is something like that :

Your viemodel :

```<code>public class ViewModel
{
    public ViewModel()
    {
        SourceList = new ObservableCollection<BusinessAdapter>();

        for (int i = 0; i < 50; i++)
        {
            SourceList.Add(new BusinessAdapter { BusinessProperty = "blabla_" + i });
        }
    }
    public ObservableCollection<BusinessAdapter> SourceList { get; private set; }
}
</code>```

You're view code behind

```<code>public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        DataContext = new ViewModel();

    }
}
</code>```

And then in your view. The important stuff here is ' ItemsSource="{Binding SourceList}" ' which basically means "the source collection of my listbox is the the collection of my datacontext (which is a Viewmodel object) named SourceList"

```<code>        <ListView x:Name="listOne"
              Grid.Column="0"
              Width="50"
              Height="200"
              ItemsSource="{Binding SourceList}"  />
</code>```

Body:
I'm David. I don`t know to bind collection to datagrid in XAML for a WPF application.

below are classes.

class TestSetting(): INotifyChanged
{
   private a
   public double A
   {
      get a;
      set a = value;
      Notify("A");
   }

   private b
   public double B
   {
      get b;
      set b = value;
      Notify("B");
   }

   private c
   public double C
   {
      get c;
      set c = value;
      Notify("C");
   }

}

class TestCollect():ObservableCollection<T> ,INotifyListener
{

}

above code is Psedo code.

DataContext has 7 items. So the grid will have 7 columns. Could someone please help me with an example or a code snippet.

Body:
I think that what you need is something like that :

Your viemodel :

public class ViewModel
{
    public ViewModel()
    {
        SourceList = new ObservableCollection<BusinessAdapter>();

        for (int i = 0; i < 50; i++)
        {
            SourceList.Add(new BusinessAdapter { BusinessProperty = "blabla_" + i });
        }
    }
    public ObservableCollection<BusinessAdapter> SourceList { get; private set; }
}

You're view code behind

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        DataContext = new ViewModel();

    }
}

And then in your view. The important stuff here is ' ItemsSource="{Binding SourceList}" ' which basically means "the source collection of my listbox is the the collection of my datacontext (which is a Viewmodel object) named SourceList"

        <ListView x:Name="listOne"
              Grid.Column="0"
              Width="50"
              Height="200"
              ItemsSource="{Binding SourceList}"  />


问:
JavaFX Exception in thread "main" java.lang.NoClassDefFoundError: javafx/application/Application
I'm getting this error

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: javafx/application/Ap
plication
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: javafx.application.Application
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 13 more
</code>```

When trying to run my class file, this is the source

```<code>import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.util.concurrent.Executor;

public class TestApplication extends Application{

    @Override
    public void start(Stage stage) throws Exception {
        new TestApplication();
    }

    public TestApplication() {
        try{
            final Parent root = FXMLLoader.load(Executor.class.getResource("test.fxml"));
            final Stage stage = new Stage(){{
                setScene(new Scene(root, 300, 250));
                setTitle("Test");
                setResizable(false);
                show();
            }};
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
</code>```

The fxml file contains a simple gui.

答:
in eclipse environment: add jfxrt.jar to Bundle-ClassPath in MANIFEST.MF file.</p>

```<code>Bundle-ClassPath: .,
jfxrt.jar
</code>```

Body:
I'm getting this error

Exception in thread "main" java.lang.NoClassDefFoundError: javafx/application/Ap
plication
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: javafx.application.Application
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 13 more

When trying to run my class file, this is the source

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.util.concurrent.Executor;

public class TestApplication extends Application{

    @Override
    public void start(Stage stage) throws Exception {
        new TestApplication();
    }

    public TestApplication() {
        try{
            final Parent root = FXMLLoader.load(Executor.class.getResource("test.fxml"));
            final Stage stage = new Stage(){{
                setScene(new Scene(root, 300, 250));
                setTitle("Test");
                setResizable(false);
                show();
            }};
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

The fxml file contains a simple gui.

Body:
in eclipse environment: add jfxrt.jar to Bundle-ClassPath in MANIFEST.MF file.

Bundle-ClassPath: .,
jfxrt.jar


问:
How can I include a header file that contains `>` in its name?
This is quite a contrived problem, I admit, but here it is.

Suppose you have a file with the > character in its name. This is possible on most Unix systems afaik:

```<code>$ touch 'weird>name'
$ ls -l
-rw-r--r--  1 user  user   0 28 Mag 11:05 weird>name
</code>```

Now, suppose this file contains C/C++ code and you want to include it as an header:

```<code>#include <weird>name>

int main() {
  return weird_function();
}
</code>```

Clang gives me the following error:

```<code>test.cpp:1:10: fatal error: 'weird' file not found
#include <weird>name>
</code>```

Of course, since the preprocessor parses the directive up to the first > and looks for the weird file. But, I wonder if some escaping mechanism exists to allow me to include the right file.

So, in C and/or C++, is there a way to include an header file which has the > character in its name?

Edit: Many suggested me why not to use #include "weird>name". I admit that my mind slipped over the quotes syntax while writing the question, but it remains valid because the two syntaxes may ask the compiler to search in different paths (theoretically at least). So is there any escaping mechanism to let me include weird>name using the #include <> syntax?

答:
Ask the author of your compiler.

The C and C++ standards grant a lot of leeway to implementations over the interpretation of #include directives. There's no requirement that #include <foo.h> causes the inclusion of a file called "foo.h". For instance, a compiler can choose to ROT13 all the source file names if it likes. And for non-alphanumeric characters, the implementation can identify and remap certain character sequences. So if there were a platform where > regularly showed up in filenames, it's likely that a compiler for that platform would specify that, say, \g or something would be remapped to >. But the standard doesn't mandate a particular encoding.

Incidentally, the implementation could also just choose to allow #include <weird>name>. Since that is not well-formed under the language standards, an implementation is free to define a meaning for it as an extension.

Body:
This is quite a contrived problem, I admit, but here it is.

Suppose you have a file with the > character in its name. This is possible on most Unix systems afaik:

$ touch 'weird>name'
$ ls -l
-rw-r--r--  1 user  user   0 28 Mag 11:05 weird>name

Now, suppose this file contains C/C++ code and you want to include it as an header:

#include <weird>name>

int main() {
  return weird_function();
}

Clang gives me the following error:

test.cpp:1:10: fatal error: 'weird' file not found
#include <weird>name>

Of course, since the preprocessor parses the directive up to the first > and looks for the weird file. But, I wonder if some escaping mechanism exists to allow me to include the right file.

So, in C and/or C++, is there a way to include an header file which has the > character in its name?

Edit: Many suggested me why not to use #include "weird>name". I admit that my mind slipped over the quotes syntax while writing the question, but it remains valid because the two syntaxes may ask the compiler to search in different paths (theoretically at least). So is there any escaping mechanism to let me include weird>name using the #include <> syntax?


问:
How To Mount Directory Of Conainter Into Another After containers are run?
I have angular app, which is built when container is run as shown in Dockerfile, that's built from two images.

```<code>FROM node:10.15.3-alpine as builder

RUN mkdir -p /usr/src/banax_education_platform
WORKDIR /usr/src/banax_education_platform

RUN apk add git
COPY package*.json /usr/src/banax_education_platform/
RUN npm i

COPY . /usr/src/banax_education_platform

RUN npm i -g @angular/cli && npm run-script build

FROM nginx:1.13.12-alpine

RUN rm -rf /usr/share/nginx/html/*

COPY /nginx/default.conf /etc/nginx/conf.d/default.conf

COPY --from=builder /usr/src/banax_education_platform/dist/edu-app /usr/share/nginx/html

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
</code>```

So first of all, it fetches node image and build the app with all requirments. and then it fetches another image of nginx and creates server block to show the app. Now I want to split both images, so one container holds angular app and second does nginx reverse proxy.

Came up with this docker-compose.yml

```<code>version: "2"
services:
 nginx:
  build: ./nginx
  container_name: angular-nginx
  ports:
   - "80:80"
  volumes:
   - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
  depends_on:
   - web
 web:
  build: ./angular
  container_name: angular-app
  ports:
   - "8000"
</code>```

But the issue is, I want this task:
COPY --from=builder /usr/src/banax_education_platform/dist/edu-app /usr/share/nginx/html to be done via docker-compose, cause now I have 2 Dockerfiles, one for angular, and one for nginx, so I don't know how to link that angular container's directory with nginx container. Someone has any idea?

答:
In a typical Web application, you run some sort of packager (for instance, Webpack) that "compiles" your application down to a set of static files.  You then need some Web server to send those files to clients, but nothing runs that code on the server side once it's built.

This matches the multi-stage Docker image that you show in the question pretty well.  The first stage only builds artifacts, and once it's done, nothing ever runs the image it builds.  (Note for example the lack of CMD.)  The second stage COPY --from=build the static artifacts it builds, and that's it.

Since there's no actual application to run in the first stage, it doesn't make sense to run this as a separate Docker Compose service or to otherwise "split this up" in the way you're showing.

If you don't mind having multiple build tools, one thing you can do is to treat the packaged application as "data" from the point of view of Nginx (it doesn't know anything about the content of these files, it just sends data over the network).  You can pick some directory on your host and mount that into the Nginx container

```<code>version: "3"
services:
  nginx:
    image: nginx:1.13.12-alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
      - ./dist:/usr/share/nginx/html
</code>```

and then npm run-script build on your host system when you need to rebuild and redeploy the application.

Body:
I have angular app, which is built when container is run as shown in Dockerfile, that's built from two images.

FROM node:10.15.3-alpine as builder

RUN mkdir -p /usr/src/banax_education_platform
WORKDIR /usr/src/banax_education_platform

RUN apk add git
COPY package*.json /usr/src/banax_education_platform/
RUN npm i

COPY . /usr/src/banax_education_platform

RUN npm i -g @angular/cli && npm run-script build

FROM nginx:1.13.12-alpine

RUN rm -rf /usr/share/nginx/html/*

COPY /nginx/default.conf /etc/nginx/conf.d/default.conf

COPY --from=builder /usr/src/banax_education_platform/dist/edu-app /usr/share/nginx/html

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

So first of all, it fetches node image and build the app with all requirments. and then it fetches another image of nginx and creates server block to show the app. Now I want to split both images, so one container holds angular app and second does nginx reverse proxy.

Came up with this docker-compose.yml

version: "2"
services:
 nginx:
  build: ./nginx
  container_name: angular-nginx
  ports:
   - "80:80"
  volumes:
   - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
  depends_on:
   - web
 web:
  build: ./angular
  container_name: angular-app
  ports:
   - "8000"

But the issue is, I want this task:
COPY --from=builder /usr/src/banax_education_platform/dist/edu-app /usr/share/nginx/html to be done via docker-compose, cause now I have 2 Dockerfiles, one for angular, and one for nginx, so I don't know how to link that angular container's directory with nginx container. Someone has any idea?

Body:
In a typical Web application, you run some sort of packager (for instance, Webpack) that "compiles" your application down to a set of static files.  You then need some Web server to send those files to clients, but nothing runs that code on the server side once it's built.

This matches the multi-stage Docker image that you show in the question pretty well.  The first stage only builds artifacts, and once it's done, nothing ever runs the image it builds.  (Note for example the lack of CMD.)  The second stage COPY --from=build the static artifacts it builds, and that's it.

Since there's no actual application to run in the first stage, it doesn't make sense to run this as a separate Docker Compose service or to otherwise "split this up" in the way you're showing.

If you don't mind having multiple build tools, one thing you can do is to treat the packaged application as "data" from the point of view of Nginx (it doesn't know anything about the content of these files, it just sends data over the network).  You can pick some directory on your host and mount that into the Nginx container

version: "3"
services:
  nginx:
    image: nginx:1.13.12-alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
      - ./dist:/usr/share/nginx/html

and then npm run-script build on your host system when you need to rebuild and redeploy the application.


答:
File objects have a readAsDataURL method.

Use that.

```<code>  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener("load", function () {
    doSomethingWithAUrl(reader.result);
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
</code>```

Title: How to work with the url of a fileReader object?

Body:
File objects have a readAsDataURL method.

Use that.

  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener("load", function () {
    doSomethingWithAUrl(reader.result);
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }


答:
It depends on what you need to do with your map.
Allowing accessing it directly to map (so setting that as public), will give anyone the possibility do use and modify that map without any restriction.

In your case the map is final and immutable, so this won't apply.

But if you want to restrict that access only to some of its content, like the title, then the right choice is to create a method that will return only a String.

Setting the map to public, or creating a method which return the whole map makes no difference.

Body:
I have a utility class which contains a static final map with some values. I need to access to this map in another class. Should I just declare the map as public, or should I write a getter inside the utility class, and therefore let the map be private?

Both ways work, but what are the best practices?

public MyUtilityClass {
  public static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

}

public MyAnotherClass {

  public void someMethod() {
    //accessing the map directly
    MAX_LENGTHS.get("title")
  }

}

Or

public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static final getMaxLengthMap() {return MAX_LENGTHS;}
}

public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLengthMap().get("title")
  }
}

Well, actually the keys are enum values.
Something like :

private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      MyEnumClass.TITLE, 256,
      MyEnumClass.TEXT, 512);


问:
Decrypting Apple VAS Data received
I have sending data from NFC Pass to POS terminal where i have included encryptionPublicKey. I have been trying to decrypt the Apple VAS only Data received on NFC POS terminal.
i am not aware of these encryption and decryption processes.
Can anyone help on this to decrypt the data received?</p>

答:
You need to implement Apple's VAS protocol to get the decrypted data along with following their decryption steps, which are under NDA, to decrypt the returned data. Sorry I could not be more help.

I work for PassNinja, we are trying to make this process easier for developers for NFC enabled Apple and Google Wallet passes.

Title: Decrypting Apple VAS Data received


问:
Buffer filling last empty spaces in char array with unwanted data
```<code>FILE* file_;
        char buffer[5];
                file_ = fopen("Data.txt", "a+");
        while (!feof(file_))
        {
            fread(buffer, sizeof(buffer), 1, file_);
            cout << buffer<<" ";
            BM(buffer, pat);
        }
</code>```

Data.txt="ABCC1ABCC2XXX"

Output:

ABCC1m

ABCC2m

XXXC2m

How can I make buffer stop before it starts generating chars from previous buffer?(bolded font part)

Wanted output:

ABCC1

ABCC2

XXX

答:
You have two problems.  Firstly you are not null-terminating buffer at all, (which is why you are getting the m output.  Secondly, you are not null-terminating buffer in the right place when there is a short read.

fread will tell you how many characters it has read, and you need to put the '\0' there.  Edit  That previous description is not accurate.  It tells you how many objects it has read, each of size arg2, and you read upto arg3 of them.  You need to change the arguments to fread so that you are reading single characters, and as many of them as there room in the buffer.  So:

```<code>        FILE* file_;
        char buffer[5+1];
                file_ = fopen("Data.txt", "a+");
        while (!feof(file_))
        {
            const size_t nchars = fread(buffer, 1, sizeof(buffer)-1, file_);
            buffer[nchars] = '\0';
            cout << buffer<<" ";
            BM(buffer, pat);
        }
</code>```

Pedantic note:  The second argument to fread could also be written as sizeof(buffer[0]) if buffer is of something other than char/signed char/unsigned char - but those three are defined to have a sizeof 1.

Body:
FILE* file_;
        char buffer[5];
                file_ = fopen("Data.txt", "a+");
        while (!feof(file_))
        {
            fread(buffer, sizeof(buffer), 1, file_);
            cout << buffer<<" ";
            BM(buffer, pat);
        }

Data.txt="ABCC1ABCC2XXX"

Output:

ABCC1m

ABCC2m

XXXC2m

How can I make buffer stop before it starts generating chars from previous buffer?(bolded font part)

Wanted output:

ABCC1

ABCC2

XXX

Body:
You have two problems.  Firstly you are not null-terminating buffer at all, (which is why you are getting the m output.  Secondly, you are not null-terminating buffer in the right place when there is a short read.

fread will tell you how many characters it has read, and you need to put the '\0' there.  Edit  That previous description is not accurate.  It tells you how many objects it has read, each of size arg2, and you read upto arg3 of them.  You need to change the arguments to fread so that you are reading single characters, and as many of them as there room in the buffer.  So:

        FILE* file_;
        char buffer[5+1];
                file_ = fopen("Data.txt", "a+");
        while (!feof(file_))
        {
            const size_t nchars = fread(buffer, 1, sizeof(buffer)-1, file_);
            buffer[nchars] = '\0';
            cout << buffer<<" ";
            BM(buffer, pat);
        }

Pedantic note:  The second argument to fread could also be written as sizeof(buffer[0]) if buffer is of something other than char/signed char/unsigned char - but those three are defined to have a sizeof 1.