问:
Kill child process when parent process is killed
I'm creating new processes using System.Diagnostics.Process class from my application.

 I want this processes to be killed when/if my application has crashed. But if I kill my application from Task Manager, child processes are not killed.

 Is there any way to make child processes dependent on parent process?

答:
I was looking for a solution to this problem that did not require unmanaged code. I was also not able to use standard input/output redirection because it was a Windows Forms application.

My solution was to create a named pipe in the parent process and then connect the child process to the same pipe. If the parent process exits then the pipe becomes broken and the child can detect this.

Below is an example using two console applications:

Parent

```<code>private const string PipeName = "471450d6-70db-49dc-94af-09d3f3eba529";

public static void Main(string[] args)
{
    Console.WriteLine("Main program running");

    using (NamedPipeServerStream pipe = new NamedPipeServerStream(PipeName, PipeDirection.Out))
    {
        Process.Start("child.exe");

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}
</code>```

Child

```<code>private const string PipeName = "471450d6-70db-49dc-94af-09d3f3eba529"; // same as parent

public static void Main(string[] args)
{
    Console.WriteLine("Child process running");

    using (NamedPipeClientStream pipe = new NamedPipeClientStream(".", PipeName, PipeDirection.In))
    {
        pipe.Connect();
        pipe.BeginRead(new byte[1], 0, 1, PipeBrokenCallback, pipe);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}

private static void PipeBrokenCallback(IAsyncResult ar)
{
    // the pipe was closed (parent process died), so exit the child process too

    try
    {
        NamedPipeClientStream pipe = (NamedPipeClientStream)ar.AsyncState;
        pipe.EndRead(ar);
    }
    catch (IOException) { }

    Environment.Exit(1);
}
</code>```

Body:
I was looking for a solution to this problem that did not require unmanaged code. I was also not able to use standard input/output redirection because it was a Windows Forms application.

My solution was to create a named pipe in the parent process and then connect the child process to the same pipe. If the parent process exits then the pipe becomes broken and the child can detect this.

Below is an example using two console applications:

Parent

private const string PipeName = "471450d6-70db-49dc-94af-09d3f3eba529";

public static void Main(string[] args)
{
    Console.WriteLine("Main program running");

    using (NamedPipeServerStream pipe = new NamedPipeServerStream(PipeName, PipeDirection.Out))
    {
        Process.Start("child.exe");

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}

Child

private const string PipeName = "471450d6-70db-49dc-94af-09d3f3eba529"; // same as parent

public static void Main(string[] args)
{
    Console.WriteLine("Child process running");

    using (NamedPipeClientStream pipe = new NamedPipeClientStream(".", PipeName, PipeDirection.In))
    {
        pipe.Connect();
        pipe.BeginRead(new byte[1], 0, 1, PipeBrokenCallback, pipe);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}

private static void PipeBrokenCallback(IAsyncResult ar)
{
    // the pipe was closed (parent process died), so exit the child process too

    try
    {
        NamedPipeClientStream pipe = (NamedPipeClientStream)ar.AsyncState;
        pipe.EndRead(ar);
    }
    catch (IOException) { }

    Environment.Exit(1);
}


来源: stackexchange

问:
Getting Gmail API access and ID token, but refresh token is NULL
Following https://developers.google.com/identity/sign-in/web/server-side-flow After getting the authorization code from JavaScript, and passing it to the server side, we indeed get an access token (and an ID token), but not the required refresh token.

There are many posts around but could not solve it yet.

Any suggestion how to get the refresh token?

thanks!

```<code>    private String getResponseToken(GoogleClientSecrets clientSecrets,
                                                 String authCode) throws IOException {
        try {
            GoogleTokenResponse tokenResponse =
                    new GoogleAuthorizationCodeTokenRequest(
                            new NetHttpTransport(),
                            JacksonFactory.getDefaultInstance(),
                            "https://www.googleapis.com/oauth2/v4/token",
//                        "https://accounts.google.com/o/oauth2/token",
                            clientSecrets.getDetails().getClientId(),
                            clientSecrets.getDetails().getClientSecret(),

                            authCode, //NOTE: was received from JavaScript client

                            "postmessage" //TODO: what's this?
                            ).execute();
            String accessToken = tokenResponse.getAccessToken();
            String idToken = tokenResponse.getIdToken();

            //TODO: not getting a refresh token... why?!
            String refreshToken = tokenResponse.getRefreshToken();
            Boolean hasRefreshToken = new Boolean(!(refreshToken == null));
            LOGGER.warn("received refresh token: {}", hasRefreshToken);

            LOGGER.debug("accessToken: {}, refreshToken: {}, idToken: {}", accessToken, refreshToken, idToken);
            return accessToken;
        }catch (TokenResponseException tre){...}
</code>```

答:
after finding how to use the Google APIs at the backend (documentation is somewhat partial..), the issue was fixed at the FrontEnd side by tweaking a parameter:

grantOfflineAccess({
-            prompt: 'select_account'
+            prompt: 'consent'

HTH

ContentLicense: CC BY-SA 3.0

Body:
Following https://developers.google.com/identity/sign-in/web/server-side-flow After getting the authorization code from JavaScript, and passing it to the server side, we indeed get an access token (and an ID token), but not the required refresh token.

There are many posts around but could not solve it yet.

Any suggestion how to get the refresh token?

thanks!

    private String getResponseToken(GoogleClientSecrets clientSecrets,
                                                 String authCode) throws IOException {
        try {
            GoogleTokenResponse tokenResponse =
                    new GoogleAuthorizationCodeTokenRequest(
                            new NetHttpTransport(),
                            JacksonFactory.getDefaultInstance(),
                            "https://www.googleapis.com/oauth2/v4/token",
//                        "https://accounts.google.com/o/oauth2/token",
                            clientSecrets.getDetails().getClientId(),
                            clientSecrets.getDetails().getClientSecret(),

                            authCode, //NOTE: was received from JavaScript client

                            "postmessage" //TODO: what's this?
                            ).execute();
            String accessToken = tokenResponse.getAccessToken();
            String idToken = tokenResponse.getIdToken();

            //TODO: not getting a refresh token... why?!
            String refreshToken = tokenResponse.getRefreshToken();
            Boolean hasRefreshToken = new Boolean(!(refreshToken == null));
            LOGGER.warn("received refresh token: {}", hasRefreshToken);

            LOGGER.debug("accessToken: {}, refreshToken: {}, idToken: {}", accessToken, refreshToken, idToken);
            return accessToken;
        }catch (TokenResponseException tre){...}


问:
Docker seems to ignore DOCKER_HOST and other vars set from `eval $(docker-machine env)`
I am on OS X, with docker installed through brew.  Trying to use the combination of docker-machine and docker.  Docker seems to ignore my environment settings.  How can I fix this?

```<code>   $ docker-machine env default2
   export DOCKER_TLS_VERIFY="1"
   export DOCKER_HOST="tcp://192.168.99.100:2376"
   export DOCKER_CERT_PATH="/Users/kasterma/.docker/machine/machines/default2"
   export DOCKER_MACHINE_NAME="default2"
   # Run this command to configure your shell:
   # eval $(docker-machine env default2)

   $ eval $(docker-machine env default2)
</code>```

My understanding is that now everything is set up in the shell as it should be to use docker.  However:

```<code>   $ docker ps
   Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
</code>```

If I specify everything on the command line it works

```<code>   $ docker -H tcp://192.168.99.100:2376 --tls --tlscacert /Users/kasterma/.docker/machine/machines/default2/ca.pem --tlscert /Users/kasterma/.docker/machine/machines/default2/cert.pem --tlskey /Users/kasterma/.docker/machine/machines/default2/key.pem ps
   CONTAINER ID        NAMES               IMAGE               STATUS
</code>```

Together they seem to indicate the environment variables are ignored.  Note that they are set correctly (the more indented parts of the output here are, I believe, from the command line completion).

```<code>   $ set | grep DOCK
   DOCKER_CERT_PATH=/Users/kasterma/.docker/machine/machines/default2
   DOCKER_HOST=tcp://192.168.99.100:2376
   DOCKER_MACHINE_NAME=default2
   DOCKER_TLS_VERIFY=1
               if [ "${DOCKER_COMPLETION_SHOW_CONTAINER_IDS}" = yes ]; then
       case "$DOCKER_COMPLETION_SHOW_IMAGE_IDS" in
       if [ "${DOCKER_COMPLETION_SHOW_TAGS:-yes}" = "yes" ]; then
       case "$DOCKER_COMPLETION_SHOW_IMAGE_IDS" in
       if test ${DOCKER_MACHINE_NAME}; then
           if test ${DOCKER_MACHINE_PS1_SHOWSTATUS:-false} = true; then
               status=$(docker-machine status ${DOCKER_MACHINE_NAME});
           printf -- "${format}" "${DOCKER_MACHINE_NAME}${status}";
                   echo "Active machine: ${DOCKER_MACHINE_NAME}"
               if [ "${DOCKER_COMPLETION_SHOW_NETWORK_IDS}" = yes ]; then
       [ "${DOCKER_COMPLETION_SHOW_NODE_IDS}" = yes ] && fields='$1,$2';
       if [ "$DOCKER_COMPLETION_SHOW_PLUGIN_IDS" = yes ]; then
               if [ "$DOCKER_COMPLETION_SHOW_SECRET_IDS" = yes ]; then
       [ "${DOCKER_COMPLETION_SHOW_SERVICE_IDS}" = yes ] && fields='$1,$2';
       [ -z "$DOCKER_HIDE_LEGACY_COMMANDS" ] && commands+=(${legacy_commands[*]});
       if  ${DOCKER_MACHINE_WRAPPED} = true ; then
</code>```

Here is my docker version information

```<code>$ docker -H tcp://192.168.99.100:2376 --tls --tlscacert /Users/kasterma/.docker/machine/machines/default2/ca.pem --tlscert /Users/kasterma/.docker/machine/machines/default2/cert.pem --tlskey /Users/kasterma/.docker/machine/machines/default2/key.pem version
Client:
 Version:      17.05.0-ce
 API version:  1.29
 Go version:   go1.8.1
 Git commit:   89658be
 Built:
 OS/Arch:      darwin/amd64

Server:
 Version:      17.05.0-ce
 API version:  1.29 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 21:43:09 2017
 OS/Arch:      linux/amd64
 Experimental: false
</code>```

And showing the docker binaries linking to the brew versions (with some stuff left over from having run the OS X version of docker before).

```<code>$ ls -l dock*
lrwxr-xr-x 1 kasterma admin       35 Jun  5 12:14 docker -> ../Cellar/docker/17.05.0/bin/docker
lrwxr-xr-x 1 kasterma admin       50 Jun  5 12:15 docker-compose -> ../Cellar/docker-compose/1.13.0/bin/docker-compose
-rwxr-xr-x 1 kasterma admin  4938393 Dec  4  2015 docker-compose.backup
lrwxr-xr-x 1 kasterma staff       91 Jun  5 11:54 docker-credential-osxkeychain -> '/Users/kasterma/Library/Group Containers/group.com.docker/bin/docker-credential-osxkeychain'
lrwxr-xr-x 1 kasterma admin       50 Jun  5 12:12 docker-machine -> ../Cellar/docker-machine/0.11.0/bin/docker-machine
-rwxr-xr-x 1 kasterma admin  7417984 Dec  1  2015 docker-machine-driver-amazonec2
-rwxr-xr-x 1 kasterma admin  8112752 Dec  1  2015 docker-machine-driver-azure
-rwxr-xr-x 1 kasterma admin  7355040 Dec  1  2015 docker-machine-driver-digitalocean
-rwxr-xr-x 1 kasterma admin  7343472 Dec  1  2015 docker-machine-driver-exoscale
-rwxr-xr-x 1 kasterma admin  7471952 Dec  1  2015 docker-machine-driver-generic
-rwxr-xr-x 1 kasterma admin 10575760 Dec  1  2015 docker-machine-driver-google
-rwxr-xr-x 1 kasterma admin  7362496 Dec  1  2015 docker-machine-driver-hyperv
-rwxr-xr-x 1 kasterma admin  6830912 Dec  1  2015 docker-machine-driver-none
-rwxr-xr-x 1 kasterma admin  7709792 Dec  1  2015 docker-machine-driver-openstack
-rwxr-xr-x 1 kasterma admin  7778992 Dec  1  2015 docker-machine-driver-rackspace
-rwxr-xr-x 1 kasterma admin  7328400 Dec  1  2015 docker-machine-driver-softlayer
-rwxr-xr-x 1 kasterma admin  8046416 Dec  1  2015 docker-machine-driver-virtualbox
-rwxr-xr-x 1 kasterma admin  7907168 Dec  1  2015 docker-machine-driver-vmwarefusion
-rwxr-xr-x 1 kasterma admin  7545600 Dec  1  2015 docker-machine-driver-vmwarevcloudair
-rwxr-xr-x 1 kasterma admin  7449392 Dec  1  2015 docker-machine-driver-vmwarevsphere
-rwxr-xr-x 1 kasterma admin  9039648 Dec  1  2015 docker-machine.backup
-rwxr-xr-x 1 kasterma admin  9231840 Dec  4  2015 docker.backup
</code>```

答:
From the comments, your docker command was aliased to sudo docker. The sudo command will not pass through the environment variables defined by docker-machine so it will default back to the /var/lib/docker.sock.

As for which vs type, which will point to a binary in the $PATH to let you know where something is located. type will let you know how the shell is running that command including shell built-ins, any aliases, or function definitions.

To solve this, remove the alias from your bash scripts and launch a new shell. In an existing shell that has the alias, you can run unalias docker or /usr/local/bin/docker (with the full path). In environments where you used sudo, consider adding the user to the docker group with:

sudo usermod -aG docker `whoami` && newgrp docker

That will give you group level access to the docker socket so you don't need to run sudo for the docker commands.

Body:
I am on OS X, with docker installed through brew.  Trying to use the combination of docker-machine and docker.  Docker seems to ignore my environment settings.  How can I fix this?

   $ docker-machine env default2
   export DOCKER_TLS_VERIFY="1"
   export DOCKER_HOST="tcp://192.168.99.100:2376"
   export DOCKER_CERT_PATH="/Users/kasterma/.docker/machine/machines/default2"
   export DOCKER_MACHINE_NAME="default2"
   # Run this command to configure your shell:
   # eval $(docker-machine env default2)

   $ eval $(docker-machine env default2)

My understanding is that now everything is set up in the shell as it should be to use docker.  However:

   $ docker ps
   Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

If I specify everything on the command line it works

   $ docker -H tcp://192.168.99.100:2376 --tls --tlscacert /Users/kasterma/.docker/machine/machines/default2/ca.pem --tlscert /Users/kasterma/.docker/machine/machines/default2/cert.pem --tlskey /Users/kasterma/.docker/machine/machines/default2/key.pem ps
   CONTAINER ID        NAMES               IMAGE               STATUS

Together they seem to indicate the environment variables are ignored.  Note that they are set correctly (the more indented parts of the output here are, I believe, from the command line completion).

   $ set | grep DOCK
   DOCKER_CERT_PATH=/Users/kasterma/.docker/machine/machines/default2
   DOCKER_HOST=tcp://192.168.99.100:2376
   DOCKER_MACHINE_NAME=default2
   DOCKER_TLS_VERIFY=1
               if [ "${DOCKER_COMPLETION_SHOW_CONTAINER_IDS}" = yes ]; then
       case "$DOCKER_COMPLETION_SHOW_IMAGE_IDS" in
       if [ "${DOCKER_COMPLETION_SHOW_TAGS:-yes}" = "yes" ]; then
       case "$DOCKER_COMPLETION_SHOW_IMAGE_IDS" in
       if test ${DOCKER_MACHINE_NAME}; then
           if test ${DOCKER_MACHINE_PS1_SHOWSTATUS:-false} = true; then
               status=$(docker-machine status ${DOCKER_MACHINE_NAME});
           printf -- "${format}" "${DOCKER_MACHINE_NAME}${status}";
                   echo "Active machine: ${DOCKER_MACHINE_NAME}"
               if [ "${DOCKER_COMPLETION_SHOW_NETWORK_IDS}" = yes ]; then
       [ "${DOCKER_COMPLETION_SHOW_NODE_IDS}" = yes ] && fields='$1,$2';
       if [ "$DOCKER_COMPLETION_SHOW_PLUGIN_IDS" = yes ]; then
               if [ "$DOCKER_COMPLETION_SHOW_SECRET_IDS" = yes ]; then
       [ "${DOCKER_COMPLETION_SHOW_SERVICE_IDS}" = yes ] && fields='$1,$2';
       [ -z "$DOCKER_HIDE_LEGACY_COMMANDS" ] && commands+=(${legacy_commands[*]});
       if  ${DOCKER_MACHINE_WRAPPED} = true ; then

Here is my docker version information

$ docker -H tcp://192.168.99.100:2376 --tls --tlscacert /Users/kasterma/.docker/machine/machines/default2/ca.pem --tlscert /Users/kasterma/.docker/machine/machines/default2/cert.pem --tlskey /Users/kasterma/.docker/machine/machines/default2/key.pem version
Client:
 Version:      17.05.0-ce
 API version:  1.29
 Go version:   go1.8.1
 Git commit:   89658be
 Built:
 OS/Arch:      darwin/amd64

Server:
 Version:      17.05.0-ce
 API version:  1.29 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 21:43:09 2017
 OS/Arch:      linux/amd64
 Experimental: false

And showing the docker binaries linking to the brew versions (with some stuff left over from having run the OS X version of docker before).

$ ls -l dock*
lrwxr-xr-x 1 kasterma admin       35 Jun  5 12:14 docker -> ../Cellar/docker/17.05.0/bin/docker
lrwxr-xr-x 1 kasterma admin       50 Jun  5 12:15 docker-compose -> ../Cellar/docker-compose/1.13.0/bin/docker-compose
-rwxr-xr-x 1 kasterma admin  4938393 Dec  4  2015 docker-compose.backup
lrwxr-xr-x 1 kasterma staff       91 Jun  5 11:54 docker-credential-osxkeychain -> '/Users/kasterma/Library/Group Containers/group.com.docker/bin/docker-credential-osxkeychain'
lrwxr-xr-x 1 kasterma admin       50 Jun  5 12:12 docker-machine -> ../Cellar/docker-machine/0.11.0/bin/docker-machine
-rwxr-xr-x 1 kasterma admin  7417984 Dec  1  2015 docker-machine-driver-amazonec2
-rwxr-xr-x 1 kasterma admin  8112752 Dec  1  2015 docker-machine-driver-azure
-rwxr-xr-x 1 kasterma admin  7355040 Dec  1  2015 docker-machine-driver-digitalocean
-rwxr-xr-x 1 kasterma admin  7343472 Dec  1  2015 docker-machine-driver-exoscale
-rwxr-xr-x 1 kasterma admin  7471952 Dec  1  2015 docker-machine-driver-generic
-rwxr-xr-x 1 kasterma admin 10575760 Dec  1  2015 docker-machine-driver-google
-rwxr-xr-x 1 kasterma admin  7362496 Dec  1  2015 docker-machine-driver-hyperv
-rwxr-xr-x 1 kasterma admin  6830912 Dec  1  2015 docker-machine-driver-none
-rwxr-xr-x 1 kasterma admin  7709792 Dec  1  2015 docker-machine-driver-openstack
-rwxr-xr-x 1 kasterma admin  7778992 Dec  1  2015 docker-machine-driver-rackspace
-rwxr-xr-x 1 kasterma admin  7328400 Dec  1  2015 docker-machine-driver-softlayer
-rwxr-xr-x 1 kasterma admin  8046416 Dec  1  2015 docker-machine-driver-virtualbox
-rwxr-xr-x 1 kasterma admin  7907168 Dec  1  2015 docker-machine-driver-vmwarefusion
-rwxr-xr-x 1 kasterma admin  7545600 Dec  1  2015 docker-machine-driver-vmwarevcloudair
-rwxr-xr-x 1 kasterma admin  7449392 Dec  1  2015 docker-machine-driver-vmwarevsphere
-rwxr-xr-x 1 kasterma admin  9039648 Dec  1  2015 docker-machine.backup
-rwxr-xr-x 1 kasterma admin  9231840 Dec  4  2015 docker.backup


问:
Django's ManyToMany Relationship with Additional Fields
I want to store some additional information in that, automatically created, ManyToMany join-table. How would I do that in Django?

In my case I have two tables: "Employees" and "Projects". What I want to store is how much each of the employees receives per hour of work in each of the projects, since those values are not the same. So, how would I do that?

What occurred to me was to, instead of the method "ManyToManyField", create explicitly a third class/table to store those new informations and to set its relationship with "Employees" and "Projects" using the "ForeignKey" method. I'm pretty sure it will work, but is this the best approach?

答:
Here is example of what you want to achieve:

http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

In case link ever breaks:

```<code>from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)
</code>```

Body:
Here is example of what you want to achieve:

http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

In case link ever breaks:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)


问:
Web Application with React and Express
I am a new Nodejs developer and I wanted to understand a few things about creating a web app with react and express.

I want to do the following:

-> My web applications will have around 5 static pages which include the home page, about us page etc. From my reading, I understand that these static pages will need to be rendered server side for SEO optimization.

-> I am also creating a user dashboard which will be made completely in react to serve as a single page application once the user logs in.

-> Thirdly, I also want to have a portion of the web app render different content based on url. For example: mywebsite/test1 should render content about test1 while mywebsite/test2 should render content about test2. I understand that this can be done through react but because I also want these urls to be SEO so the content will have to be rendered serverside.

How would I go setting up such an application? My initial thoughts are as follows:

Have an express app where I have routes defined for the 5 static pages. I can render html directly for these 5 pages.

For the dashboard, I can have an express route forward the request to react/react router and take it from there.

Similarly for the 3rd part I was use the express route to direct to a react component.

Is this the right way to go about it?

Thanks! Do let me know if I missing something or if I'm conceptually wrong about something.

答:
All I understand is that you're doing some kind of isomorphic app.

Static pages can be pre-rendered at build (index.html, about.html, etc)

Serve static files from a subfolder (i.e. /assets)

When requested URL is prefixed with i.e. /dashboard, make express serve your dashboard:

http://example/dashboard/some/view => /dashboard.html

In your dashboard, you'll probably use React Router.
Your Router will then dispatch URLs to desired components:

import { Route } from 'react-router';
import SomeView from 'app/components/some/SomeView.jsx';
<Route path='/dashboard/some/view' render={SomeView} />

You'll find a lot of examples on GitHub or articles here or here related to isomorphic apps.

Title: Web Application with React and Express


问:
How to merge css or How to use class in JS instead of id
In One of My application for input field I am geeting this design.

Pic
My code

```<code><input class="myCombo-combobox" name="language" style="width:30%;">
</code>```

My CSS

```<code>.textbox {
  position: relative;
  border: 1px solid #95B8E7;
  background-color: #fff;
  vertical-align: middle;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
.textbox .textbox-text {
  font-size: 12px;
  border: 0;
  margin: 0;
  padding: 4px;
  white-space: normal;
  vertical-align: top;
  outline-style: none;
  resize: none;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
.textbox .textbox-text::-ms-clear,
.textbox .textbox-text::-ms-reveal {
  display: none;
}
.textbox textarea.textbox-text {
  white-space: pre-wrap;
}
.textbox .textbox-prompt {
  font-size: 12px;
  color: #aaa;
}
.textbox .textbox-bgicon {
  background-position: 3px center;
  padding-left: 21px;
}

.textbox-addon {
  position: absolute;
  top: 0;
}

.textbox-label-after {
  padding-left: 5px;
  padding-right: 0;
}
.textbox-label-top {
  display: block;
  width: auto;
  padding: 0;
}
.textbox-disabled,
.textbox-label-disabled {
  opacity: 0.6;
  filter: alpha(opacity=60);
}

.combo-arrow {
  width: 18px;
  height: 20px;
  overflow: hidden;
  display: inline-block;
  vertical-align: top;
  cursor: pointer;
  opacity: 0.6;
  filter: alpha(opacity=60);
}
.combo-arrow-hover {
  opacity: 1.0;
  filter: alpha(opacity=100);
}
.combo-panel {
  overflow: auto;
}
.combo-arrow {
  background: url('images/combo_arrow.png') no-repeat center center;
}
.combo-panel {
  background-color: #ffffff;
}
.combo-arrow {
  background-color: #E0ECFF;
}
.combo-arrow-hover {
  background-color: #eaf2ff;
}
.combo-arrow:hover {
  background-color: #eaf2ff;
}
.combo .textbox-icon-disabled:hover {
  cursor: default;
}
.combobox-item,
.combobox-group,
.combobox-stick {
  font-size: 12px;
  padding: 3px;
}
.combobox-item-disabled {
  opacity: 0.5;
  filter: alpha(opacity=50);
}
.combobox-gitem {
  padding-left: 10px;
}
.combobox-group,
.combobox-stick {
  font-weight: bold;
}
.combobox-stick {
  position: absolute;
  top: 1px;
  left: 1px;
  right: 1px;
  background: inherit;
}
.combobox-item-hover {
  background-color: #eaf2ff;
  color: #000000;
}
.combobox-item-selected {
  background-color: #ffe48d;
  color: #000000;
}
.combobox-icon {
  display: inline-block;
  width: 16px;
  height: 16px;
  vertical-align: middle;
  margin-right: 2px;
}
</code>```

The other places I am creating my input field like this way

Pic

```<code>var myTable = '<input type="text" class="combobox"; style="width:30%;" id="myInput" onkeyup="myFunction()" title="Type in a name">' +
    '<table id="myTable">' + '<tr class="header"></tr>' + '<tr><td></td></tr>' + '</table>';
</code>```

My CSS

```<code>* {
  box-sizing: border-box;
}
#myInput {
  background-image: url('Drop.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 30%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
#tdiv{
    height : 30%;
    overflow-y:auto;

}

tbody {
  display: block;
}

tbody {
  max-height: 150px;
  overflow: auto;
}
#myTable {
  border-collapse: collapse;
  width: 30%;
  border: 1px solid #ddd;
  font-size: 18px;
  display: none;
  margin-top:-12px;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
  width : 10%;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
  order-top: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}

#myInput:focus + #myTable{
  display: block;
}

#myTable:hover{
 display: block;
}
</code>```

For My second application also I want the first kind of design. How to make with css because I am using id insted of class.
2. Is it possible that input data from table should be underlined and ";" seperated.

答:
Use the same class for the same styling. You can use class and id together. A class is used to put the same styles for many items and id is a unique identifier.

If you want a drop down, use

```<code><select class="myCombo-combobox" name="language" style="width:30%;" id="myInput" onkeyup="myFunction()">
    <option> A </option>
    <option> B </option>
    <option> C </option>
</select>
</code>```

Body:
In One of My application for input field I am geeting this design.

Pic
My code

<input class="myCombo-combobox" name="language" style="width:30%;">

My CSS

.textbox {
  position: relative;
  border: 1px solid #95B8E7;
  background-color: #fff;
  vertical-align: middle;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
.textbox .textbox-text {
  font-size: 12px;
  border: 0;
  margin: 0;
  padding: 4px;
  white-space: normal;
  vertical-align: top;
  outline-style: none;
  resize: none;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
.textbox .textbox-text::-ms-clear,
.textbox .textbox-text::-ms-reveal {
  display: none;
}
.textbox textarea.textbox-text {
  white-space: pre-wrap;
}
.textbox .textbox-prompt {
  font-size: 12px;
  color: #aaa;
}
.textbox .textbox-bgicon {
  background-position: 3px center;
  padding-left: 21px;
}

.textbox-addon {
  position: absolute;
  top: 0;
}

.textbox-label-after {
  padding-left: 5px;
  padding-right: 0;
}
.textbox-label-top {
  display: block;
  width: auto;
  padding: 0;
}
.textbox-disabled,
.textbox-label-disabled {
  opacity: 0.6;
  filter: alpha(opacity=60);
}

.combo-arrow {
  width: 18px;
  height: 20px;
  overflow: hidden;
  display: inline-block;
  vertical-align: top;
  cursor: pointer;
  opacity: 0.6;
  filter: alpha(opacity=60);
}
.combo-arrow-hover {
  opacity: 1.0;
  filter: alpha(opacity=100);
}
.combo-panel {
  overflow: auto;
}
.combo-arrow {
  background: url('images/combo_arrow.png') no-repeat center center;
}
.combo-panel {
  background-color: #ffffff;
}
.combo-arrow {
  background-color: #E0ECFF;
}
.combo-arrow-hover {
  background-color: #eaf2ff;
}
.combo-arrow:hover {
  background-color: #eaf2ff;
}
.combo .textbox-icon-disabled:hover {
  cursor: default;
}
.combobox-item,
.combobox-group,
.combobox-stick {
  font-size: 12px;
  padding: 3px;
}
.combobox-item-disabled {
  opacity: 0.5;
  filter: alpha(opacity=50);
}
.combobox-gitem {
  padding-left: 10px;
}
.combobox-group,
.combobox-stick {
  font-weight: bold;
}
.combobox-stick {
  position: absolute;
  top: 1px;
  left: 1px;
  right: 1px;
  background: inherit;
}
.combobox-item-hover {
  background-color: #eaf2ff;
  color: #000000;
}
.combobox-item-selected {
  background-color: #ffe48d;
  color: #000000;
}
.combobox-icon {
  display: inline-block;
  width: 16px;
  height: 16px;
  vertical-align: middle;
  margin-right: 2px;
}

The other places I am creating my input field like this way

Pic

var myTable = '<input type="text" class="combobox"; style="width:30%;" id="myInput" onkeyup="myFunction()" title="Type in a name">' +
    '
' + '

' + '

' + '
';

My CSS

* {
  box-sizing: border-box;
}
#myInput {
  background-image: url('Drop.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 30%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
#tdiv{
    height : 30%;
    overflow-y:auto;

}

tbody {
  display: block;
}

tbody {
  max-height: 150px;
  overflow: auto;
}
#myTable {
  border-collapse: collapse;
  width: 30%;
  border: 1px solid #ddd;
  font-size: 18px;
  display: none;
  margin-top:-12px;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
  width : 10%;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
  order-top: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}

#myInput:focus + #myTable{
  display: block;
}

#myTable:hover{
 display: block;
}

For My second application also I want the first kind of design. How to make with css because I am using id insted of class.
2. Is it possible that input data from table should be underlined and ";" seperated.

Body:
Use the same class for the same styling. You can use class and id together. A class is used to put the same styles for many items and id is a unique identifier.

If you want a drop down, use

<select class="myCombo-combobox" name="language" style="width:30%;" id="myInput" onkeyup="myFunction()">
    <option> A </option>
    <option> B </option>
    <option> C </option>
</select>


问:
This type of CollectionView does not support changes to its SourceCollection from a thread... while using the dispatcher?
So Im developing an addon with a UI that is used inside an application (main application). To make my UI responsive when the main application is working I'm starting my UI in its separate thread like this:

```<code>    public  void ShowDialog(IIFCConverter ifcConverter)
    {

        thread = new Thread(x =>
        {
            thread.Name = "UI-thread";
            window = new MainWindow();
            var mainViewModel = ServiceLocator.Current.GetInstance<MainWindowViewModel>();
            mainViewModel.SetIFCConverter(x as IIFCConverter);
            ViewModelLocator.MainWindow = window;
            window.ShowDialog();

        });
        thread.SetApartmentState(ApartmentState.STA);

        thread.Start(ifcConverter);

    }
</code>```

The first time I start my addon it all works. The second time I start it and it tries to raise events (like OnCollectionChanged) I get a NotSupportedException with the message: "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread"

This is one of my methods:

```<code>    private void AddNewFile(AddNewFileMessage obj)
    {
        if (!(obj.Sender is ButtonViewModel)) return;

        if (string.IsNullOrEmpty(obj.Path)) return;

        var ifcFileViewModel = new IFCFileViewModel(new Common.Model.IFCFile { Path = obj.Path, Active = true });
        DispatcherHelper.CheckBeginInvokeOnUI(() =>
        {
            ListBoxItems.Insert(ListBoxItems.Count - 1, ifcFileViewModel);
        });

    }
</code>```

I get this eventhough Im using the DispatcherHelper from MVVM light.
I have tried using the "normal" dispatcher to, but that gives me the same result.

First of all Im curious to know the mechanics of why its doing this?
I've checked my threads and I can see that the OnOllectionChanged is called from my UI-thread.
I cant seem to find any differences to the thread structure between the first run (that works) and the following.

Second, what can I do about this?

Things that I've tested that didnt help:

Im using the IoC container from MVVM light and its registered as a LocatorProvider, but I create a new IoC container everytime I initialize the UI and set that instance as the LocatorProvider.

Im initializing the DispatcherHelper in the constructor of my window. So that should be on the correct thread.

Something that does actually work is wrapping the action in a try Catch-block like this:

```<code>private void AddNewFile(AddNewFileMessage obj)
{
if (!(obj.Sender is ButtonViewModel)) return;

if (string.IsNullOrEmpty(obj.Path)) return;

var ifcFileViewModel = new IFCFileViewModel(new Common.Model.IFCFile { Path = obj.Path, Active = true });

DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
    try
    {
        ListBoxItems.Insert(ListBoxItems.Count - 1, ifcFileViewModel);
    }
    catch(Exception ex)
    {

    }
});
</code>```

}

However I find this very ugly and would like to avoid it and why does that even work? Everything seems to work fine when I wrap all my actions in try Catch-blocks.

答: Take a look at the BindingOperations.EnableCollectionSynchronization and read this topic: Using BindingOperations.EnableCollectionSynchronization.</p>

Body:
So Im developing an addon with a UI that is used inside an application (main application). To make my UI responsive when the main application is working I'm starting my UI in its separate thread like this:

    public  void ShowDialog(IIFCConverter ifcConverter)
    {

        thread = new Thread(x =>
        {
            thread.Name = "UI-thread";
            window = new MainWindow();
            var mainViewModel = ServiceLocator.Current.GetInstance<MainWindowViewModel>();
            mainViewModel.SetIFCConverter(x as IIFCConverter);
            ViewModelLocator.MainWindow = window;
            window.ShowDialog();

        });
        thread.SetApartmentState(ApartmentState.STA);

        thread.Start(ifcConverter);

    }

The first time I start my addon it all works. The second time I start it and it tries to raise events (like OnCollectionChanged) I get a NotSupportedException with the message: "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread"

This is one of my methods:

    private void AddNewFile(AddNewFileMessage obj)
    {
        if (!(obj.Sender is ButtonViewModel)) return;

        if (string.IsNullOrEmpty(obj.Path)) return;

        var ifcFileViewModel = new IFCFileViewModel(new Common.Model.IFCFile { Path = obj.Path, Active = true });
        DispatcherHelper.CheckBeginInvokeOnUI(() =>
        {
            ListBoxItems.Insert(ListBoxItems.Count - 1, ifcFileViewModel);
        });

    }

I get this eventhough Im using the DispatcherHelper from MVVM light.
I have tried using the "normal" dispatcher to, but that gives me the same result.

First of all Im curious to know the mechanics of why its doing this?
I've checked my threads and I can see that the OnOllectionChanged is called from my UI-thread.
I cant seem to find any differences to the thread structure between the first run (that works) and the following.

Second, what can I do about this?

Things that I've tested that didnt help:

Im using the IoC container from MVVM light and its registered as a LocatorProvider, but I create a new IoC container everytime I initialize the UI and set that instance as the LocatorProvider.

Im initializing the DispatcherHelper in the constructor of my window. So that should be on the correct thread.

Something that does actually work is wrapping the action in a try Catch-block like this:

private void AddNewFile(AddNewFileMessage obj)
{
if (!(obj.Sender is ButtonViewModel)) return;

if (string.IsNullOrEmpty(obj.Path)) return;

var ifcFileViewModel = new IFCFileViewModel(new Common.Model.IFCFile { Path = obj.Path, Active = true });

DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
    try
    {
        ListBoxItems.Insert(ListBoxItems.Count - 1, ifcFileViewModel);
    }
    catch(Exception ex)
    {

    }
});

}

However I find this very ugly and would like to avoid it and why does that even work? Everything seems to work fine when I wrap all my actions in try Catch-blocks.


问:
select query to get all values based on distinct values using linq
I have n number of services and under each service there will be 2 routes(some times more than 2). Under each route there are n number of stops. I am getting values from db as  a table in below column order
ServiceId, Service Name,serviceLine color,RouteId, Route Name, Stop Id, Stop Name, Latitude, Longitude.

I want to convert it an object list of below format

 public class Service
    {
        public string ServiceId { get; set; }
        public string ServiceName { get; set; }
        public string ServiceLineColor { get; set; }
        public List<RouteData> RouteList { get; set; }
    }
    public class RouteData
    {
        public string RouteId { get; set; }
        public string RouteCode { get; set; }
        public string RouteName { get; set; }
        public List<StopData> stopList { get; set; }
    }
    public class StopData
    {
        public string StopCode { get; set; }
        public string StopName { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string StopType { get; set; }
    }```

Is there any easy way in linq to convert data in to below format? I wanted to avoid looping.. since i am getting nearly 1k records from db. Please help me to solve this issue.

Or is it best to use db calls to format data. i didn't prefer that because if there is 50 services i need to do 50 db calls and again have to do data formatting logic.

答:
To avoid looping over the data structure each time, you could build up additional dictionaries that provide fast access of the objects by id:</p>

```<code>var myServiceIndex = new Dictionary<string, Service>()
var myRouteDataIndex = new Dictionary<string, RouteData>()

Service service;
RouteData routData;

foreach (var record in databaseRecords)
{
    if (myRouteDataIndex.TryGetValue(record.RouteId, out route))
    {
        // add stop data
    }
    else if (myServiceIndex.TryGetValue(record.ServiceId, out service)
    {
        // add route data
        // add stop data
    }
    else
    {
        // add service
        // add route data
        // add stop data
    }
}
</code>```

Body:
I have n number of services and under each service there will be 2 routes(some times more than 2). Under each route there are n number of stops. I am getting values from db as  a table in below column order
ServiceId, Service Name,serviceLine color,RouteId, Route Name, Stop Id, Stop Name, Latitude, Longitude.

I want to convert it an object list of below format

 public class Service
    {
        public string ServiceId { get; set; }
        public string ServiceName { get; set; }
        public string ServiceLineColor { get; set; }
        public List<RouteData> RouteList { get; set; }
    }
    public class RouteData
    {
        public string RouteId { get; set; }
        public string RouteCode { get; set; }
        public string RouteName { get; set; }
        public List<StopData> stopList { get; set; }
    }
    public class StopData
    {
        public string StopCode { get; set; }
        public string StopName { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string StopType { get; set; }
    }

Is there any easy way in linq to convert data in to below format? I wanted to avoid looping.. since i am getting nearly 1k records from db. Please help me to solve this issue.

Or is it best to use db calls to format data. i didn't prefer that because if there is 50 services i need to do 50 db calls and again have to do data formatting logic.

Body:
To avoid looping over the data structure each time, you could build up additional dictionaries that provide fast access of the objects by id:

var myServiceIndex = new Dictionary<string, Service>()
var myRouteDataIndex = new Dictionary<string, RouteData>()

Service service;
RouteData routData;

foreach (var record in databaseRecords)
{
    if (myRouteDataIndex.TryGetValue(record.RouteId, out route))
    {
        // add stop data
    }
    else if (myServiceIndex.TryGetValue(record.ServiceId, out service)
    {
        // add route data
        // add stop data
    }
    else
    {
        // add service
        // add route data
        // add stop data
    }
}


问:
Packaging java project
I have one java project with two class. One of them is with main method. I also have two files one of them is a.properties and second one i b.xls. The way I want to export this project is in one executable jar but withour these two files(a.properties and b.xls) being compressed inside this executable jar. The reason for this is, user who run this project should able to change the properties file(a.properties) and also excel file(b.xls). I also want to include the libraries I have used for this project.

I am using Eclipse helios and jdk 1.6.

I really appreciate if somebody will provide me the steps for this. I already tried the Export option with executable jar but it compress everything including two files.

Thanks

答: With eclipse you can simply go to the project explorer.  Right click the project name and select export.  Under Java, click runnable jar file (or just jar file if that is what you want).  Follow the prompts and you are done.</p>

ContentLicense: CC BY-SA 2.5

Title: Packaging java project


问:
How to create typeahead feature in JavaScript
CSS
TypeAhead

I am trying to create a comboBox in HTML and JavaScript.

So I create an input field and then inside the input field I created a table. On click of input I am getting a drop down where my table is getting displayed. I can select the td value from table.

Here is my JavaScript code:

```<code>Myocombo = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);
    var myTable = '<input type="text" style="width:30%;" id="myInput" onkeyup="myFunction()" title="Type in a name">' +
        '<table id="myTable">' + '<tr class="header"></tr>' + '<tr><td></td></tr>' + '</table>';
    div.innerHTML = myTable;
    function foo(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', "data.json", true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }
    // Getting data from URL
    foo(function(data) {
        debugger;
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '<tr><td>' + jsonc[i]['VALUE'] + '</td></tr>';
        }
        document.getElementById('myTable').innerHTML = new_opt;
        document.querySelectorAll('#myTable tr:not(.header)').forEach(function(_tr) {
            _tr.addEventListener('click', function() {
                document.getElementById('myInput').value += " ; " + this.getElementsByTagName('td')[0].textContent;
            });
        });
    });
    // Displaying the table name
    myFunction = function() {
        var input, filter, table, tr, td, i;
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
}
</code>```

Now I want a typeahead feature. Meaning if I type anything other td value can filter and show those values only. How can I do that?

My HTML code:

```<code><!DOCTYPE html>
<meta charset="utf-8">

<head>
    <title>PC-AutoCombo </title>
    <link rel="stylesheet" type="text/css" href="css/Myocombo .css">
    <script src="js/Myocombo.js"></script>
</head>
<body>
    <select id="mySelect" onchange="myFunction()">
        <option value="Line">Line</option>
        <option value="Bar">Bar</option>
    </select>
    <div id="chart_line" style = "position: relative;"></div>

</body>
<script>
    function myFunction(){
        var val = document.getElementById("mySelect").value;
            switch(val){
                case 'Line' :
                    var myCombo = new Myocombo ({
                      "url": "data.json",
                      "divID": "chart_line",
                    });
                    break;
                case 'Bar' :
                    var myCombo = new Myocombo ({
                      "url": "data.json",
                      "divID": "chart_line",
                    });
                    break;

            }
    }
</script>
</code>```

Is there any jQuery way by which I can get this?

My JSON data:

```<code>[
    {
        "ID" : 0,
        "VALUE" : "United State"
    },{
        "ID"  : 1,
        "VALUE" : "United Kingdom"
    },{
        "ID"  : 2,
        "VALUE" : "Afghanistan"
    },{
        "ID"  : 3,
        "VALUE" : "Aland Islands"
    },{
        "ID"  : 4,
        "VALUE" : "Albania"
    },{
        "ID" : 5,
        "VALUE" : "United State"
    },{
        "ID"  : 6,
        "VALUE" : "United Kingdom"
    },{
        "ID"  : 7,
        "VALUE" : "Afghanistan"
    },{
        "ID"  : 8,
        "VALUE" : "Aland Islands"
    },{
        "ID"  : 9,
        "VALUE" : "Albania"
    },{
        "Data" : "Hello"
    }
]
</code>```

答:
Try jQuery's UI Autocomplete...</p>

```<code>  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
CSS
TypeAhead

I am trying to create a comboBox in HTML and JavaScript.

So I create an input field and then inside the input field I created a table. On click of input I am getting a drop down where my table is getting displayed. I can select the td value from table.

Here is my JavaScript code:

Myocombo = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);
    var myTable = '<input type="text" style="width:30%;" id="myInput" onkeyup="myFunction()" title="Type in a name">' +
        '
' + '

' + '

' + '
';
    div.innerHTML = myTable;
    function foo(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', "data.json", true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }
    // Getting data from URL
    foo(function(data) {
        debugger;
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '
' + jsonc[i]['VALUE'] + '
';
        }
        document.getElementById('myTable').innerHTML = new_opt;
        document.querySelectorAll('#myTable tr:not(.header)').forEach(function(_tr) {
            _tr.addEventListener('click', function() {
                document.getElementById('myInput').value += " ; " + this.getElementsByTagName('td')[0].textContent;
            });
        });
    });
    // Displaying the table name
    myFunction = function() {
        var input, filter, table, tr, td, i;
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i
 -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
}

Now I want a typeahead feature. Meaning if I type anything other td value can filter and show those values only. How can I do that?

My HTML code:

<!DOCTYPE html>
<meta charset="utf-8">

    <title>PC-AutoCombo </title>
    <link rel="stylesheet" type="text/css" href="css/Myocombo .css">

    <select id="mySelect" onchange="myFunction()">
        <option value="Line">Line</option>
        <option value="Bar">Bar</option>
    </select>

Is there any jQuery way by which I can get this?

My JSON data:

[
    {
        "ID" : 0,
        "VALUE" : "United State"
    },{
        "ID"  : 1,
        "VALUE" : "United Kingdom"
    },{
        "ID"  : 2,
        "VALUE" : "Afghanistan"
    },{
        "ID"  : 3,
        "VALUE" : "Aland Islands"
    },{
        "ID"  : 4,
        "VALUE" : "Albania"
    },{
        "ID" : 5,
        "VALUE" : "United State"
    },{
        "ID"  : 6,
        "VALUE" : "United Kingdom"
    },{
        "ID"  : 7,
        "VALUE" : "Afghanistan"
    },{
        "ID"  : 8,
        "VALUE" : "Aland Islands"
    },{
        "ID"  : 9,
        "VALUE" : "Albania"
    },{
        "Data" : "Hello"
    }
]

Body:
Try jQuery's UI Autocomplete...

  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );


问:
Iterable associative array object
I have a need for a list type object simultaneously providing the contrary JS array behaviours of being iterable and associative.  So at one point I want to run an index based walk through the members and in another I want to do 'does this key exist' and 'update the data under that key'.

I see many question in SO regarding discussions about associative arrays but this question differs because I am seeking re-usable code that wraps both behaviours. The solution can be a modifier to the array prototype, or a stand-alone object creation function. I accept that the list must be unique by key, and FYI in my case the members will be objects themselves.

Please note I know that there is no such thing as an associative array in JavaScript - I don't need that sermon. I seek the a solution for a single object with both capabilities on the same list.

Here is a rudimentary version in a working snippet. I am looking for a more fleshed out version that includes the full set of life-cycle features such as disposal, etc..

var List = function() {
  this.elements={} // assoc list of elements.
  this.elementArray=[] // plain array
  this.addElement=function (id, member) {
    this.elements[id]=member;
    this.elementArray.push(member);
    }
}

var myList = new List();

myList.addElement('V', {id: 'key2', name: 'Volvo'});
myList.addElement('A', {id: 'key4', name: 'Apple'});
myList.addElement('S', {id: 'key3', name: 'Google'});

console.log('Via iteration');
for (var i = 0; i < myList.elementArray.length; i = i + 1) {
  console.log('id=' + myList.elementArray[i].id + ' name=' + myList.elementArray[i].name);
}

console.log('Via association');
console.log('Value of A: id=' + myList.elements['A'].id + ' name=' + myList.elements['A'].name);
console.log('Value of V: id=' + myList.elements['V'].id + ' name=' + myList.elements['V'].name);
console.log('Value of S: id=' + myList.elements['S'].id + ' name=' + myList.elements['S'].name);```

答:
I know this is far away from done, but it might give you a starting point, extending the Array class gives you the array's special length property (adds on push, when its modified it modifies the array itself, etc)

'use strict';

class AssociativeArray extends Array {
   constructor() {
      super();
      this.data = {};
   }
   push(key, value) {
      super.push(key);
      this.data[key] = value
   }
   *[Symbol.iterator]() {
      let nextIndex = 0;
      while(nextIndex < this.length) {
        yield this[nextIndex];
        nextIndex++;
      }
   }
}

var myAssociativeArray = new AssociativeArray();
myAssociativeArray.push("1st", "Bamieh");
myAssociativeArray.push("2nd", "value");
myAssociativeArray.push("3nd", "anotherValue");
console.log('myAssociativeArray::', myAssociativeArray);
console.log('myAssociativeArray.length::', myAssociativeArray.length);

for (let key of myAssociativeArray) {
  console.log('key::', key);
}```

basically you are reimplementing the Map or the Set functions, which are natively supported in es6. its a good practice non-the-less.

Title: Iterable associative array object

Body:
I know this is far away from done, but it might give you a starting point, extending the Array class gives you the array's special length property (adds on push, when its modified it modifies the array itself, etc)

'use strict';

class AssociativeArray extends Array {
   constructor() {
      super();
      this.data = {};
   }
   push(key, value) {
      super.push(key);
      this.data[key] = value
   }
   *[Symbol.iterator]() {
      let nextIndex = 0;
      while(nextIndex < this.length) {
        yield this[nextIndex];
        nextIndex++;
      }
   }
}

var myAssociativeArray = new AssociativeArray();
myAssociativeArray.push("1st", "Bamieh");
myAssociativeArray.push("2nd", "value");
myAssociativeArray.push("3nd", "anotherValue");
console.log('myAssociativeArray::', myAssociativeArray);
console.log('myAssociativeArray.length::', myAssociativeArray.length);

for (let key of myAssociativeArray) {
  console.log('key::', key);
}

basically you are reimplementing the Map or the Set functions, which are natively supported in es6. its a good practice non-the-less.


问:
How to call a method within a method from another method?
In a javascript file I have this:

```<code>Work.expenses= function (params)
{
    function deleteExpenses()
    {
      //here I want to call the loadExpensesList method
    }
}

Work.expensesList= function (params)
{
    function loadExpensesList()
    {
     //this is the method I want to call
    }
}
</code>```

How do I call the loadExpensesList method in the deleteExpenses method?
Thank you!

答:
```<code>Work.expenses= function (params)
{
    function deleteExpenses()
    {
      Work.expensesList('something')();
    }
}

Work.expensesList= function (params)
{
    function loadExpensesList()
    {

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

You can try like this. But can be better by understanding the requirement.

Body:
In a javascript file I have this:

Work.expenses= function (params)
{
    function deleteExpenses()
    {
      //here I want to call the loadExpensesList method
    }
}

Work.expensesList= function (params)
{
    function loadExpensesList()
    {
     //this is the method I want to call
    }
}

How do I call the loadExpensesList method in the deleteExpenses method?
Thank you!

Body:
Work.expenses= function (params)
{
    function deleteExpenses()
    {
      Work.expensesList('something')();
    }
}

Work.expensesList= function (params)
{
    function loadExpensesList()
    {

    }
    return loadExpensesList;
}

You can try like this. But can be better by understanding the requirement.


问:
Symfony - Add text in generated form
I'd like to do something quite simple, but I can't figure out how to manage it. I have a form:

```<code>{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</code>```

There are several text field in it. I'd like to "insert" some text (like
my Text
) between two text fields (let's say between name text field and description text field). Form are generated with form builder tool. I've tried something like:

```<code>$builder
    ->add('stuffName') // works well (text field 1)
    ->add('addedText', 'text', array('label' => 'my Text')) // Trouble here!
    ->add('stuffDescription'); // works well (text field 2)
</code>```

But it generates a text field (and not a simple text). I don't care if the text is set in the form builder or directly in twig template... As long as it is between my two text fields. Any idea?

Thanks a lot!

答:
The keyword in this question is generated.

Let's assume, that you build a form generator in Symfony. You have entities like Form, Fields and Fields Items (it's options for select box or buttons for radio button field).

So you have this entities and you create a service to create a form from the data. In the service you build the form ($this->buildedForm - generated form, $page->getFormData() - put the data to the constructed form):

$this->buildedForm = $this->formFactory->create(
    'form',
    $page->getFormData(),
    ['action' => '/page/formview/' . $task->getId()]
);

foreach($fields as $field) {
    $fieldBuilderMethod = 'construct' . ucfirst($field->getType()) . 'Field';
    if (method_exists($this, $fieldBuilderMethod)) {
        $this->$fieldBuilderMethod($field);
    }
}
return $this->buildedForm;
```
<p>And you have methods for each type like (examples for Symfony 2):</p>
```private function constructInputField(FormField $field)
{
    $this->buildedForm->add(
        $field->getFieldName(),
        'text',
        [
            'label' => $field->getName(),
        ]
    );
}

private function constructTextareaField(FormField $field)
{
    $this->buildedForm->add(
        $field->getFieldName(),
        'textarea',
        [
            'label' => $field->getName(),
        ]
    );
}
```
<p>You can now create your custom form type to paste a text in the generated form (it could be placed in the form folder of your bundle and retrieved with namespace "use"):</p>
```private function constructSimpletextField(FormField $field)
{
    $this->buildedForm->add(
        $field->getFieldName(),
        new SimpletextType(),
        [
            'label' => $field->getName(),
            'data' => $field->getPlaceholder(),
        ]
    );
}
```
<p>What in this custom field?</p>
```namespace Myproject\MyBundle\Form\TaskTypes;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SimpletextType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'disabled' => true,
            'required' => false,
            'mapped' => false,
        ]);
    }

    public function getParent()
    {
        return 'text';
    }

    public function getName()
    {
        return 'simpletext';
    }
}
```
<p>And the whole magic comes out in the template. For your custom form type you need to make a custom theme (see https://symfony.com/doc/2.7/form/form_customization.html#form-customization-form-themes). And there:</p>
<pre class="lang-html prettyprint-override"><code>{% block simpletext_label %}{% endblock %}
{% block simpletext_widget %}
    <p>{{ form.vars.data }}</p>
{% endblock %}
{% block simpletext_errors %}{% endblock %}
</code>```

See, no label, no errors (it just a text) and only text in the field widget. Very handy for generated forms with dynamic template.

EDIT - Symfony 5

In Symfony 5, this solution became simplier. The form customization doesn't changes, and the php code became like this:

```<code>namespace Myproject\MyBundle\Form\TaskTypes;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SimpletextType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'disabled' => true,
            'required' => false,
            'mapped' => false,
        ]);
    }

    public function getBlockPrefix(): string
    {
        return 'simpletext';
    }
}
</code>```

It's used like this :

```<code>public function buildForm(FormBuilderInterface $builder, array $options): void {
    /* … */
    $builder->add('anykey', SimpleTextType::class, [
        'data' => "Type your text here",
    ]);
    /* … */
}
</code>```

Title: Symfony - Add text in generated form

Body:
I'd like to do something quite simple, but I can't figure out how to manage it. I have a form:

{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

There are several text field in it. I'd like to "insert" some text (like
my Text
) between two text fields (let's say between name text field and description text field). Form are generated with form builder tool. I've tried something like:

$builder
    ->add('stuffName') // works well (text field 1)
    ->add('addedText', 'text', array('label' => 'my Text')) // Trouble here!
    ->add('stuffDescription'); // works well (text field 2)

But it generates a text field (and not a simple text). I don't care if the text is set in the form builder or directly in twig template... As long as it is between my two text fields. Any idea?

Thanks a lot!

Body:
The keyword in this question is generated.

Let's assume, that you build a form generator in Symfony. You have entities like Form, Fields and Fields Items (it's options for select box or buttons for radio button field).

So you have this entities and you create a service to create a form from the data. In the service you build the form ($this->buildedForm - generated form, $page->getFormData() - put the data to the constructed form):

$this->buildedForm = $this->formFactory->create(
    'form',
    $page->getFormData(),
    ['action' => '/page/formview/' . $task->getId()]
);

foreach($fields as $field) {
    $fieldBuilderMethod = 'construct' . ucfirst($field->getType()) . 'Field';
    if (method_exists($this, $fieldBuilderMethod)) {
        $this->$fieldBuilderMethod($field);
    }
}
return $this->buildedForm;

And you have methods for each type like (examples for Symfony 2):

private function constructInputField(FormField $field)
{
    $this->buildedForm->add(
        $field->getFieldName(),
        'text',
        [
            'label' => $field->getName(),
        ]
    );
}

private function constructTextareaField(FormField $field)
{
    $this->buildedForm->add(
        $field->getFieldName(),
        'textarea',
        [
            'label' => $field->getName(),
        ]
    );
}

You can now create your custom form type to paste a text in the generated form (it could be placed in the form folder of your bundle and retrieved with namespace "use"):

private function constructSimpletextField(FormField $field)
{
    $this->buildedForm->add(
        $field->getFieldName(),
        new SimpletextType(),
        [
            'label' => $field->getName(),
            'data' => $field->getPlaceholder(),
        ]
    );
}

What in this custom field?

namespace Myproject\MyBundle\Form\TaskTypes;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SimpletextType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'disabled' => true,
            'required' => false,
            'mapped' => false,
        ]);
    }

    public function getParent()
    {
        return 'text';
    }

    public function getName()
    {
        return 'simpletext';
    }
}

And the whole magic comes out in the template. For your custom form type you need to make a custom theme (see https://symfony.com/doc/2.7/form/form_customization.html#form-customization-form-themes). And there:

{% block simpletext_label %}{% endblock %}
{% block simpletext_widget %}
    <p>{{ form.vars.data }}</p>
{% endblock %}
{% block simpletext_errors %}{% endblock %}

See, no label, no errors (it just a text) and only text in the field widget. Very handy for generated forms with dynamic template.

EDIT - Symfony 5

In Symfony 5, this solution became simplier. The form customization doesn't changes, and the php code became like this:

namespace Myproject\MyBundle\Form\TaskTypes;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SimpletextType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'disabled' => true,
            'required' => false,
            'mapped' => false,
        ]);
    }

    public function getBlockPrefix(): string
    {
        return 'simpletext';
    }
}

It's used like this :

public function buildForm(FormBuilderInterface $builder, array $options): void {
    /* … */
    $builder->add('anykey', SimpleTextType::class, [
        'data' => "Type your text here",
    ]);
    /* … */
}


问:
c libcurl POST doesn't work consistently
I am trying to POST xml data from a c program using libcurl to a website.  When I use the command line program in linux, curl like this it works fine:

curl -X POST -H 'Content-type: text/xml' -d 'my xml data' http://test.com/test.php

(I changed the actual data for security)

But as soon as I try to write c code using libcurl, it fails almost every time but succeeds every once in a while.  Here is my c code:

```<code>CURL *curl;
CURLcode res;

curl = curl_easy_init();

if(curl)
{
    curl_easy_init(curl, CURLOPT_URL, "http://test.com/test.php");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, xmlString.c_str());
    curl_easy_perform(curl);
}

curl_easy_cleanup(curl);
</code>```

I have this code in a loop that runs about every 10 seconds and it will only succeed about every 4 or 5 calls.  I get back errors from the server that say "XML Head not found".

I tried specifying the HTTP header with:

```<code>struct curl_slist *chunk = NULL
chunk = curl_slist_append(chunk, "Content-type: text/xml");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
</code>```

But I didn't have any luck.  Any ideas?

答:
Try this:</p>

```<code>CURL *curl = curl_easy_init();
if(curl)
{
    curl_easy_setopt(curl, CURLOPT_URL, "http://test.com/test.php");
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, xmlString.c_str());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, xmlString.length());
    struct curl_slist *slist = curl_slist_append(NULL, "Content-Type: text/xml; charset=utf-8"); // or whatever charset your XML is really using...
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
    curl_easy_perform(curl);
    curl_slist_free_all(slist);
    curl_easy_cleanup(curl);
}
</code>```

Body:
I am trying to POST xml data from a c program using libcurl to a website.  When I use the command line program in linux, curl like this it works fine:

curl -X POST -H 'Content-type: text/xml' -d 'my xml data' http://test.com/test.php

(I changed the actual data for security)

But as soon as I try to write c code using libcurl, it fails almost every time but succeeds every once in a while.  Here is my c code:

CURL *curl;
CURLcode res;

curl = curl_easy_init();

if(curl)
{
    curl_easy_init(curl, CURLOPT_URL, "http://test.com/test.php");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, xmlString.c_str());
    curl_easy_perform(curl);
}

curl_easy_cleanup(curl);

I have this code in a loop that runs about every 10 seconds and it will only succeed about every 4 or 5 calls.  I get back errors from the server that say "XML Head not found".

I tried specifying the HTTP header with:

struct curl_slist *chunk = NULL
chunk = curl_slist_append(chunk, "Content-type: text/xml");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);

But I didn't have any luck.  Any ideas?

Body:
Try this:

CURL *curl = curl_easy_init();
if(curl)
{
    curl_easy_setopt(curl, CURLOPT_URL, "http://test.com/test.php");
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, xmlString.c_str());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, xmlString.length());
    struct curl_slist *slist = curl_slist_append(NULL, "Content-Type: text/xml; charset=utf-8"); // or whatever charset your XML is really using...
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
    curl_easy_perform(curl);
    curl_slist_free_all(slist);
    curl_easy_cleanup(curl);
}


问:
Command Object with generics
I have a controller that has a Command Object that uses generics like so:

```<code>@Controller
@RequestMapping(value = "/first")
public class MyFirstController {

    @RequestMapping(value = "/something", method = RequestMethod.POST)
    @ResponseBody
    public ADifferentDTO doSomething(RequestDTO<MyStringObject> requestDTO, HttpServletRequest request,
            HttpServletResponse response) {

            requestDTO.getSomeObject(); // ERROR HERE

            //.. do something
    }
}
</code>```

However, this does not work. I'm assuming it does not working because of Type Erasure in Java. Is there a way I can have the Command Object use a generic?
Here is what some of the other classes might look like.

```<code>public class RequestDTO<T> {

    private T someObject;
    // some other objects here as well that are from a submitted form (not listed)

    public void setSomeObject(T someObject){
        this.someObject = someObject;
    }

    public T getSomeObject(){
        return someObject;
    }
}

public class MyStringObject {
    private String someString;

    public MyStringObject(String someString){
        this.someString = someString;
    }
    // getter and setter
}

public class MyIntegerObject {
    private Integer someInteger;
    private Integer anotherInteger;

    public MyIntegerObject(Integer someInteger, Integer anotherInteger){
        this.someInteger = someInteger;
        this.anotherInteger = anotherInteger;
    }
    // getter and setter
}
</code>```

The error I get:

java.lang.Object cannot be cast to com.test.MyStringObject

Of course if I change my RequestDTO to only use a MyStringObject it works fine.

```<code>public class RequestDTO {

    private MyStringObject someObject;
    // some other objects here as well that are from a submitted form (not listed)

    public void setSomeObject(MyStringObject someObject){
        this.someObject = someObject;
    }

    public MyStringObject getSomeObject(){
        return someObject;
    }
}
</code>```

Is there a way this can be done?

答:
You are correct, it is because of type erasure.

Probably the simplest solution is to create a RequestDTO subclasses parameterized with each of your My*Object and use it as a Command Object class.

Given your example:

```<code>@SpringBootApplication
public class So44423504Application {

    public static void main(String[] args) {
        SpringApplication.run(So44423504Application.class, args);
    }

    @RestController
    @RequestMapping(value = "/first")
    public static class MyFirstController {

        public static class MyStringRequestDTO extends RequestDTO<MyStringObject> {}

        public static class MyIntegerRequestDTO extends RequestDTO<MyIntegerObject> {}

        @PostMapping(value = "/something")
        public String doSomething(@ModelAttribute MyStringRequestDTO/*MyIntegerRequestDTO*/ requestDTO) throws JsonProcessingException {
            return new ObjectMapper().writeValueAsString(requestDTO);
        }
    }

    public static class RequestDTO<T> {
        private T someObject;
        // getter and setter
    }

    public static class MyStringObject {
        private String someString;

        public MyStringObject() { } // required since another non-default ctor is present.

        public MyStringObject(String someString){
            this.someString = someString;
        }

        // getter and setter
    }

    public static class MyIntegerObject {
        private Integer someInteger;
        private Integer anotherInteger;

        public MyIntegerObject() { } // required since another non-default ctor is present.

        public MyIntegerObject(Integer someInteger, Integer anotherInteger){
            this.someInteger = someInteger;
            this.anotherInteger = anotherInteger;
        }
        // getters and setters
    }
}
</code>```

Then it works fine:

```<code>$ curl -XPOST 'localhost:8080/first/something?someObject.someInteger=23&someObject.anotherInteger=42'
{"someObject":{"someInteger":23,"anotherInteger":42}}%

$ curl -XPOST 'localhost:8080/first/something?someObject.someString=test'
{"someObject":{"someString":"test"}}%
</code>```

Title: Command Object with generics

Body:
I have a controller that has a Command Object that uses generics like so:

@Controller
@RequestMapping(value = "/first")
public class MyFirstController {

    @RequestMapping(value = "/something", method = RequestMethod.POST)
    @ResponseBody
    public ADifferentDTO doSomething(RequestDTO<MyStringObject> requestDTO, HttpServletRequest request,
            HttpServletResponse response) {

            requestDTO.getSomeObject(); // ERROR HERE

            //.. do something
    }
}

However, this does not work. I'm assuming it does not working because of Type Erasure in Java. Is there a way I can have the Command Object use a generic?
Here is what some of the other classes might look like.

public class RequestDTO<T> {

    private T someObject;
    // some other objects here as well that are from a submitted form (not listed)

    public void setSomeObject(T someObject){
        this.someObject = someObject;
    }

    public T getSomeObject(){
        return someObject;
    }
}

public class MyStringObject {
    private String someString;

    public MyStringObject(String someString){
        this.someString = someString;
    }
    // getter and setter
}

public class MyIntegerObject {
    private Integer someInteger;
    private Integer anotherInteger;

    public MyIntegerObject(Integer someInteger, Integer anotherInteger){
        this.someInteger = someInteger;
        this.anotherInteger = anotherInteger;
    }
    // getter and setter
}

The error I get:

java.lang.Object cannot be cast to com.test.MyStringObject

Of course if I change my RequestDTO to only use a MyStringObject it works fine.

public class RequestDTO {

    private MyStringObject someObject;
    // some other objects here as well that are from a submitted form (not listed)

    public void setSomeObject(MyStringObject someObject){
        this.someObject = someObject;
    }

    public MyStringObject getSomeObject(){
        return someObject;
    }
}

Is there a way this can be done?

Body:
You are correct, it is because of type erasure.

Probably the simplest solution is to create a RequestDTO subclasses parameterized with each of your My*Object and use it as a Command Object class.

Given your example:

@SpringBootApplication
public class So44423504Application {

    public static void main(String[] args) {
        SpringApplication.run(So44423504Application.class, args);
    }

    @RestController
    @RequestMapping(value = "/first")
    public static class MyFirstController {

        public static class MyStringRequestDTO extends RequestDTO<MyStringObject> {}

        public static class MyIntegerRequestDTO extends RequestDTO<MyIntegerObject> {}

        @PostMapping(value = "/something")
        public String doSomething(@ModelAttribute MyStringRequestDTO/*MyIntegerRequestDTO*/ requestDTO) throws JsonProcessingException {
            return new ObjectMapper().writeValueAsString(requestDTO);
        }
    }

    public static class RequestDTO<T> {
        private T someObject;
        // getter and setter
    }

    public static class MyStringObject {
        private String someString;

        public MyStringObject() { } // required since another non-default ctor is present.

        public MyStringObject(String someString){
            this.someString = someString;
        }

        // getter and setter
    }

    public static class MyIntegerObject {
        private Integer someInteger;
        private Integer anotherInteger;

        public MyIntegerObject() { } // required since another non-default ctor is present.

        public MyIntegerObject(Integer someInteger, Integer anotherInteger){
            this.someInteger = someInteger;
            this.anotherInteger = anotherInteger;
        }
        // getters and setters
    }
}

Then it works fine:

$ curl -XPOST 'localhost:8080/first/something?someObject.someInteger=23&someObject.anotherInteger=42'
{"someObject":{"someInteger":23,"anotherInteger":42}}%

$ curl -XPOST 'localhost:8080/first/something?someObject.someString=test'
{"someObject":{"someString":"test"}}%


问:
Proper toolbar styling
I would like to avoid applying a style to the toolbars in all layouts, so I have a style I created for it:

```<code><style name="DarkToolbar" >
        <item name="android:textColorPrimary">@color/white</item>
        <item name="android:textColorSecondary">@color/white</item>
        <item name="android:background">@color/blue</item>
        <item name="android:elevation">4dp</item>
</style>
</code>```

And I added it to my theme as follows:

```<code><style name="Theme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/blue</item>
        <item name="colorPrimaryDark">@color/blue</item>
        <item name="colorAccent">@color/blue</item>
        <item name="android:toolbarStyle">@style/DarkToolbar</item>
</style>
</code>```

This is the resulting toolbar:

As you can see, the title and subtitle have the wrong formatting. If I remove the style from the theme and apply it directly to the toolbar in the layout, I get the following result instead:

Both images use the same style. One is applied through the app theme with

```<code><item name="android:toolbarStyle">@style/DarkToolbar</item>
</code>```

and the second one is applied directly to the toolbar with

```<code>style="@style/DarkToolbar"
</code>```

Does anyone know the reason for the difference?
Also, does anyone know why the

```<code><item name="android:textColorPrimary">@color/white</item>
<item name="android:textColorSecondary">@color/white</item>
</code>```

Are not being applied?

Thanks

答:
Add parent="Widget.AppCompat.Toolbar" to your toolbar style. It is default style for toolbar.

For example:

```<code><style name="DarkToolbar" parent="Widget.AppCompat.Toolbar">
    <item name="android:textColorPrimary">@color/white</item>
    <item name="android:textColorSecondary">@color/white</item>
    <item name="android:background">@color/blue</item>
    <item name="android:elevation">4dp</item>
</style>
</code>```

Title: Proper toolbar styling

Body:
I would like to avoid applying a style to the toolbars in all layouts, so I have a style I created for it:

And I added it to my theme as follows:

This is the resulting toolbar:

As you can see, the title and subtitle have the wrong formatting. If I remove the style from the theme and apply it directly to the toolbar in the layout, I get the following result instead:

Both images use the same style. One is applied through the app theme with

<item name="android:toolbarStyle">@style/DarkToolbar</item>

and the second one is applied directly to the toolbar with

style="@style/DarkToolbar"

Does anyone know the reason for the difference?
Also, does anyone know why the

<item name="android:textColorPrimary">@color/white</item>
<item name="android:textColorSecondary">@color/white</item>

Are not being applied?

Thanks

Body:
Add parent="Widget.AppCompat.Toolbar" to your toolbar style. It is default style for toolbar.

For example:

<style name="DarkToolbar" parent="Widget.AppCompat.Toolbar">
    <item name="android:textColorPrimary">@color/white</item>
    <item name="android:textColorSecondary">@color/white</item>
    <item name="android:background">@color/blue</item>
    <item name="android:elevation">4dp</item>
</style>


问:
RxJs Handle error when there is another request inside map
I have service for login and use it in the following way:

```<code>// LoginComponent
    this.authService.loginDb(credentials)
          .subscribe(() => {
              this.router.navigate(['/dashboard']);
            },
            (error) => {
              this.errorMessage = error.description
            });

//auth.service
public loginDb(credentials: Credentials): Observable <any> {
    //make call to third party API
    return this.auth0.client.login({
            ...
        })
        .map((resp) => {
            // here decode token and then make another request to my server for saving user
            this.token = <Token> this.jwtHelper.decodeToken(resp.idToken);
            return this.userService.createOrUpdateUser(this.token)
                .subscribe(() => {
                    this.localStorageService.set('token', resp.idToken);
                    this.localStorageService.set('decoded_token', this.token);
                    this.loggedIn = true;
                })
        })
}
</code>```

The problem is, for example there is error on my server and this.userService.createOrUpdateUser is failed then error wont handle this in LoginComponent. So, I want error to handle for inner request too. Moreover, I see that subscribe is called before second request is finished.

I believe there is some operator in rxjs for this, but I can't find it.

答:
If you replace map() with concatMap() it'll wait until its inner Observable completes. Also if the inner Observable emits an error it'll be propagated down the chain.

In general try to avoid nesting subscribe() calls.

```<code>public loginDb(credentials: Credentials): Observable <any> {
    //make call to third party API
    return this.auth0.client.login({
            ...
        })
        .do(resp => {
            this.localStorageService.set('token', resp.idToken);
            this.localStorageService.set('decoded_token', this.token);
        })
        .concatMap((resp) => {
            // here decode token and then make another request to my server for saving user
            this.token = <Token> this.jwtHelper.decodeToken(resp.idToken);
            return this.userService.createOrUpdateUser(this.token);
        })
        .do(() => {
            this.loggedIn = true;
        });
}
</code>```

A used two do()s to perform some side-effects but maybe in you particular use case you won't need them or use them in a different way.

Body:
I have service for login and use it in the following way:

// LoginComponent
    this.authService.loginDb(credentials)
          .subscribe(() => {
              this.router.navigate(['/dashboard']);
            },
            (error) => {
              this.errorMessage = error.description
            });

//auth.service
public loginDb(credentials: Credentials): Observable <any> {
    //make call to third party API
    return this.auth0.client.login({
            ...
        })
        .map((resp) => {
            // here decode token and then make another request to my server for saving user
            this.token = <Token> this.jwtHelper.decodeToken(resp.idToken);
            return this.userService.createOrUpdateUser(this.token)
                .subscribe(() => {
                    this.localStorageService.set('token', resp.idToken);
                    this.localStorageService.set('decoded_token', this.token);
                    this.loggedIn = true;
                })
        })
}

The problem is, for example there is error on my server and this.userService.createOrUpdateUser is failed then error wont handle this in LoginComponent. So, I want error to handle for inner request too. Moreover, I see that subscribe is called before second request is finished.

I believe there is some operator in rxjs for this, but I can't find it.

Body:
If you replace map() with concatMap() it'll wait until its inner Observable completes. Also if the inner Observable emits an error it'll be propagated down the chain.

In general try to avoid nesting subscribe() calls.

public loginDb(credentials: Credentials): Observable <any> {
    //make call to third party API
    return this.auth0.client.login({
            ...
        })
        .do(resp => {
            this.localStorageService.set('token', resp.idToken);
            this.localStorageService.set('decoded_token', this.token);
        })
        .concatMap((resp) => {
            // here decode token and then make another request to my server for saving user
            this.token = <Token> this.jwtHelper.decodeToken(resp.idToken);
            return this.userService.createOrUpdateUser(this.token);
        })
        .do(() => {
            this.loggedIn = true;
        });
}

A used two do()s to perform some side-effects but maybe in you particular use case you won't need them or use them in a different way.


问:
Using get() and set() in Java
I have seen several get() and set() methods used for private fields. And I also understand why its being used.

But what I dont understand is that, I have my Student class with private fields in them. So why is it when I remove the get() and set(), it still works (for example, method to print).

Or is it still working because its in the same file class? but say if I try calling the private field without defining the get() and set() method from an external class. It wont work?

This is my code with the get() and set()

```<code>public class Student {
    private String name;
    private String address;
    private String degreeName;
    private String department;
    private String yearCommence;
    private long studentID;
    private static int nextID = 901000 ;

    public String getName() {
        return name;
    }
    public String getAddress() {
        return address;
    }
    public String getDegreeName() {
        return degreeName;
    }
    public String getDepartment() {
        return department;
    }
    public String getYearCommence() {
        return yearCommence;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAddress(String address) {
        this.name = address;
    }
    public void setDegreeName(String degreeName) {
        this.degreeName = degreeName;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public void setYearCommence(String yearCommence) {
        this.department = yearCommence;
    }

    public Student(String name, String address, String degreeName, String department, String yearCommence, long StudentID) {
        this.name = name;
        this.address = address;
        this.degreeName = degreeName;
        this.department = department;
        this.yearCommence = yearCommence;
        this.studentID = nextID++;
    }

    public Student(String name, String address, String degreeName, String department, long studentID) {
        this(name, address, degreeName, department, null, studentID);
    }
    public Student(String name, String address, String degreeName, long studentID) {
        this(name, address, degreeName, null, null, studentID);
    }
    public Student(String name, String address, long studentID) {
        this(name, address, null, null, null, studentID);
    }
    public Student(String name, long studentID) {
        this(name, null, null, null, null, studentID);
    }
    public Student(long studentID) {
        this(null, null, null, null, null, studentID);
    }

    @Override
    public String toString() {
        return "StudentInfo {" + "name=" + name + ", address=" + address + ", degreeName=" + degreeName + ", department=" + department + ", commence = " + yearCommence +", "+ " "+ "studentID = " + studentID+ "}";
    }

    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();

        Student student1 = new Student("Yusuf", "jl.ANU", "IT", "CECS", null, Student.nextID);
        students.add(student1);
        System.out.println(student1);

        Student student2 = new Student("Ning", "jl.Cikini","IT", null, null, Student.nextID);
        students.add(student2);
        System.out.println(student2);

        Student student3 = new Student("Boris", "jl.Babi", Student.nextID);
        students.add(student3);
        System.out.println(student3);

        Student student4 = new Student(null, null, null, null, null, Student.nextID);
        students.add(student4);
        System.out.println(student4);
    }
}
</code>```

答:
private fields are accessible from the same class. If you want the fields to be accessed from external class then you should declare the variable with public modifier.

You are over riding toString() method in your student class which is executed every time you print the object.

mutators and accessors are used to set the read/write behavour for the fields(from external).

I suggest you to look on access modifiers in java.

Title: Using get() and set() in Java

Body:
I have seen several get() and set() methods used for private fields. And I also understand why its being used.

But what I dont understand is that, I have my Student class with private fields in them. So why is it when I remove the get() and set(), it still works (for example, method to print).

Or is it still working because its in the same file class? but say if I try calling the private field without defining the get() and set() method from an external class. It wont work?

This is my code with the get() and set()

public class Student {
    private String name;
    private String address;
    private String degreeName;
    private String department;
    private String yearCommence;
    private long studentID;
    private static int nextID = 901000 ;

    public String getName() {
        return name;
    }
    public String getAddress() {
        return address;
    }
    public String getDegreeName() {
        return degreeName;
    }
    public String getDepartment() {
        return department;
    }
    public String getYearCommence() {
        return yearCommence;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAddress(String address) {
        this.name = address;
    }
    public void setDegreeName(String degreeName) {
        this.degreeName = degreeName;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public void setYearCommence(String yearCommence) {
        this.department = yearCommence;
    }

    public Student(String name, String address, String degreeName, String department, String yearCommence, long StudentID) {
        this.name = name;
        this.address = address;
        this.degreeName = degreeName;
        this.department = department;
        this.yearCommence = yearCommence;
        this.studentID = nextID++;
    }

    public Student(String name, String address, String degreeName, String department, long studentID) {
        this(name, address, degreeName, department, null, studentID);
    }
    public Student(String name, String address, String degreeName, long studentID) {
        this(name, address, degreeName, null, null, studentID);
    }
    public Student(String name, String address, long studentID) {
        this(name, address, null, null, null, studentID);
    }
    public Student(String name, long studentID) {
        this(name, null, null, null, null, studentID);
    }
    public Student(long studentID) {
        this(null, null, null, null, null, studentID);
    }

    @Override
    public String toString() {
        return "StudentInfo {" + "name=" + name + ", address=" + address + ", degreeName=" + degreeName + ", department=" + department + ", commence = " + yearCommence +", "+ " "+ "studentID = " + studentID+ "}";
    }

    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();

        Student student1 = new Student("Yusuf", "jl.ANU", "IT", "CECS", null, Student.nextID);
        students.add(student1);
        System.out.println(student1);

        Student student2 = new Student("Ning", "jl.Cikini","IT", null, null, Student.nextID);
        students.add(student2);
        System.out.println(student2);

        Student student3 = new Student("Boris", "jl.Babi", Student.nextID);
        students.add(student3);
        System.out.println(student3);

        Student student4 = new Student(null, null, null, null, null, Student.nextID);
        students.add(student4);
        System.out.println(student4);
    }
}


问:
Refreshing a particular div with reloading the whole page in php
I need to reload a particular div without reloading the whole page.

```<code><div class="">
                        <div class="contactpagecaptchas">
                            <img src="/captcha.php?rand=<?php echo rand();?>" class="contactpagecaptchass" id='captchaimg'/>
                            <p class="change"><a href="javascript: refreshCaptcha();" class="clickto">Click to change</a></p>
                        </div>

                        <div class="contactcaptcha">
                            <input type="text" class="form-control" name="captcha" placeholder="Captcha" style="background-color: #f4f4f4;border: none;">
                        </div>
                    </div>
</code>```

Once i click on refresh captcha text box should get cleared.

答:
$('.clickto').click(function() {
  $('[name="captcha"]').val('');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="">
  <div class="contactpagecaptchas">
    <img src="/captcha.php?rand=<?php echo rand();?>" class="contactpagecaptchass" id='captchaimg' />
    <p class="change">Click to change</p>
  </div>

  <div class="contactcaptcha">
    <input type="text" class="form-control" name="captcha" placeholder="Captcha" style="background-color: #f4f4f4;border: none;">
  </div>
</div></code>```

Body:
I need to reload a particular div without reloading the whole page.

                            <img src="/captcha.php?rand=<?php echo rand();?>" class="contactpagecaptchass" id='captchaimg'/>

Click to change

                            <input type="text" class="form-control" name="captcha" placeholder="Captcha" style="background-color: #f4f4f4;border: none;">

Once i click on refresh captcha text box should get cleared.

Body:
$('.clickto').click(function() {
  $('[name="captcha"]').val('');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="">
  <div class="contactpagecaptchas">
    <img src="/captcha.php?rand=<?php echo rand();?>" class="contactpagecaptchass" id='captchaimg' />
    <p class="change"><a href="#" class="clickto">Click to change</a></p>
  </div>

  <div class="contactcaptcha">
    <input type="text" class="form-control" name="captcha" placeholder="Captcha" style="background-color: #f4f4f4;border: none;">
  </div>
</div>


问:
Is it possible to make an AIR app run on startup?
Is it possible to make my AIR app able to add itself to the list of startup programs? (I'd like to make this work on multiple platforms - namely, Windows, Mac and Linux) How would I go about doing so?</p>

答:
```<code>if (NativeApplication.supportsStartAtLogin)
{
    NativeApplication.nativeApplication.startAtLogin = true;
}
</code>```

This will start application when user logs in, not OS starts, but it's closest thing you can get.

Body:
if (NativeApplication.supportsStartAtLogin)
{
    NativeApplication.nativeApplication.startAtLogin = true;
}

This will start application when user logs in, not OS starts, but it's closest thing you can get.