问:
`docker run` on a remote host
is it possible (using the docker command or the docker-py API directly) to start a container from a remote host?

Lets assume I have two machines that have different architectures:
- A is an x86 machine
- B is an ARM machine

I would like to run a container on the B machine using my A machine. At first, I thought it was possible using this command:

```<code>[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker run hello-from-B
</code>```

But this command actually pulls the image hello-from-B and tries to run it on the machine A which ends up on some exec format error cause obviously you can't run images that are specific to ARM to an x86 machine.

Communication between machine A and B is working well. I can run commands like images or ps and it gives me the expected results:

```<code>[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker images
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
hello-from-B              <none>              fd5059044831        13 hours ago        1.26GB
</code>```

I've heard about docker-machine and haven't tried it yet, but from my understanding, this won't solve my problem.

Is there any way to achieve that using docker directly. A workaround might be to using ssh to connect to the remote host and use the docker client directly from the remote host, but I'd like to avoid this solution as much as possible.

Thanks in advance,

TL;DR;

How can DOCKER_HOST=... docker run something runs something on the DOCKER_HOST rather than running it on my local machine.

答:
As you said the connectivity is available between the servers, you can make use of Docker rich APIs.

There are 2 ways in configuring the docker daemon port

1) Configuring at /etc/default/docker file:

```<code>DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"
</code>```

2) Configuring at /etc/docker/daemon.json:

```<code>{
"hosts": ["tcp://127.0.0.1:5000", "unix:///var/run/docker.sock"]
}
</code>```

For more details on configuring docker daemon port, refer configure-docker-daemon-port

Once the Docker ports are configured, you can access the Docker APIs in the remote host.

JSON input file:

```<code>#cat container_create.json
{
  "AttachStdin": true,
  "AttachStdout": true,
  "AttachStderr": true,
  "ExposedPorts": {
    "property1": {},
    "property2": {}
  },
  "Tty": true,
  "OpenStdin": true,
  "StdinOnce": true,
  "Cmd": null,
  "Image": "ubuntu:14.04",
  "Volumes": {
    "additionalProperties": {}
  },
  "Labels": {
    "property1": "string",
    "property2": "string"
  }
}
</code>```

API to create a container:

```<code>curl -X POST http://192.168.56.101:6000/containers/create -d @container_create.json --header "Content-Type: application/json" | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   602  100    90  100   512   1737   9883 --:--:-- --:--:-- --:--:-- 10039
{
  "Warnings": null,
  "Id": "f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940"
}
</code>```

The ID generated is the container ID and status will not be active/running.

API for starting the created container.

```<code># curl -X POST http://192.168.56.101:6000/containers/f5d3273e48350/start | jq .  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
</code>```

API to check the status/inspect the container:

```<code># curl -X GET http://192.168.56.101:6000/containers/f5d3273e48350/json | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  4076    0  4076    0     0   278k      0 --:--:-- --:--:-- --:--:--  306k
{
  "NetworkSettings": {
    "Networks": {
      "bridge": {
        "MacAddress": "02:42:ac:11:00:03",
        "GlobalIPv6PrefixLen": 0,
        "GlobalIPv6Address": "",
        "IPv6Gateway": "",
        "IPAMConfig": null,
        "Links": null,
        "Aliases": null,
        "NetworkID": "689d6b65ce1b06c93b2c70f41760a3e7fb2b50697d71cd9c1f39c64c865e5fa6",
        "EndpointID": "76bf1f8638d1ff0387e6c3fe89e8ccab1670c709ad550f9acc6f46e559654bee",
        "Gateway": "172.17.0.1",
        "IPAddress": "172.17.0.3",
        "IPPrefixLen": 16
      }
    },
    "MacAddress": "02:42:ac:11:00:03",
    "SecondaryIPAddresses": null,
    "SandboxKey": "/var/run/docker/netns/24a031d9dfda",
    "Ports": {
      "0/tcp": null
    },
    "LinkLocalIPv6PrefixLen": 0,
    "LinkLocalIPv6Address": "",
    "HairpinMode": false,
    "SandboxID": "24a031d9dfda70026a875f4841269c5e790b12ccafcc11869111faa240020b99",
    "Bridge": "",
    "SecondaryIPv6Addresses": null,
    "EndpointID": "76bf1f8638d1ff0387e6c3fe89e8ccab1670c709ad550f9acc6f46e559654bee",
    "Gateway": "172.17.0.1",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "IPAddress": "172.17.0.3",
    "IPPrefixLen": 16,
    "IPv6Gateway": ""
  },

    },
    "AttachStderr": true,
    "AttachStdout": true,
    "AttachStdin": true,
    "User": "",
    "Domainname": "",
    "Hostname": "f5d3273e4835",
    "OpenStdin": true,
    "StdinOnce": true,
    "Env": [
      "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
    ],
    "Cmd": [
      "/bin/bash"
    ],
    "ArgsEscaped": true,
    "Image": "ubuntu:14.04",

<*************REMOVING THE OUTPUT CONTENT********>

  "ExecIDs": null,
  "HostnamePath": "/var/lib/docker/containers/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940/hostname",
  "ResolvConfPath": "/var/lib/docker/containers/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940/resolv.conf",
  "Image": "sha256:132b7427a3b40f958aaeae8716e0cbb2177658d2410554ed142e583ef522309f",
  "State": {
    "FinishedAt": "0001-01-01T00:00:00Z",
    "StartedAt": "2017-06-09T06:53:45.120357144Z",
    "Error": "",
    "Status": "running",
    "Running": true,
    "Paused": false,
    "Restarting": false,

  "Path": "/bin/bash",
  "Created": "2017-06-09T06:52:51.820429355Z",
  "Id": "f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940",
  "HostsPath": "/var/lib/docker/containers/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940/hosts",
  "LogPath": "/var/lib/docker/containers/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940-json.log",
  "Name": "/objective_bartik",
  "RestartCount": 0,
  "Driver": "aufs",
  "MountLabel": "",
  "ProcessLabel": "",
  "AppArmorProfile": "docker-default"
}
</code>```

Refer this for more info:

DOCKER APIs

How to build an Image using Docker API?

How to commit Docker Container using API

Hope this info will he helpful.

Title: `docker run` on a remote host

Body:
is it possible (using the docker command or the docker-py API directly) to start a container from a remote host?

Lets assume I have two machines that have different architectures:
- A is an x86 machine
- B is an ARM machine

I would like to run a container on the B machine using my A machine. At first, I thought it was possible using this command:

[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker run hello-from-B

But this command actually pulls the image hello-from-B and tries to run it on the machine A which ends up on some exec format error cause obviously you can't run images that are specific to ARM to an x86 machine.

Communication between machine A and B is working well. I can run commands like images or ps and it gives me the expected results:

[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker images
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
hello-from-B              <none>              fd5059044831        13 hours ago        1.26GB

I've heard about docker-machine and haven't tried it yet, but from my understanding, this won't solve my problem.

Is there any way to achieve that using docker directly. A workaround might be to using ssh to connect to the remote host and use the docker client directly from the remote host, but I'd like to avoid this solution as much as possible.

Thanks in advance,

TL;DR;

How can DOCKER_HOST=... docker run something runs something on the DOCKER_HOST rather than running it on my local machine.

Body:
As you said the connectivity is available between the servers, you can make use of Docker rich APIs.

There are 2 ways in configuring the docker daemon port

1) Configuring at /etc/default/docker file:

DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"

2) Configuring at /etc/docker/daemon.json:

{
"hosts": ["tcp://127.0.0.1:5000", "unix:///var/run/docker.sock"]
}

For more details on configuring docker daemon port, refer configure-docker-daemon-port

Once the Docker ports are configured, you can access the Docker APIs in the remote host.

JSON input file:

#cat container_create.json
{
  "AttachStdin": true,
  "AttachStdout": true,
  "AttachStderr": true,
  "ExposedPorts": {
    "property1": {},
    "property2": {}
  },
  "Tty": true,
  "OpenStdin": true,
  "StdinOnce": true,
  "Cmd": null,
  "Image": "ubuntu:14.04",
  "Volumes": {
    "additionalProperties": {}
  },
  "Labels": {
    "property1": "string",
    "property2": "string"
  }
}

API to create a container:

curl -X POST http://192.168.56.101:6000/containers/create -d @container_create.json --header "Content-Type: application/json" | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   602  100    90  100   512   1737   9883 --:--:-- --:--:-- --:--:-- 10039
{
  "Warnings": null,
  "Id": "f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940"
}

The ID generated is the container ID and status will not be active/running.

API for starting the created container.

# curl -X POST http://192.168.56.101:6000/containers/f5d3273e48350/start | jq .  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current

API to check the status/inspect the container:

# curl -X GET http://192.168.56.101:6000/containers/f5d3273e48350/json | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  4076    0  4076    0     0   278k      0 --:--:-- --:--:-- --:--:--  306k
{
  "NetworkSettings": {
    "Networks": {
      "bridge": {
        "MacAddress": "02:42:ac:11:00:03",
        "GlobalIPv6PrefixLen": 0,
        "GlobalIPv6Address": "",
        "IPv6Gateway": "",
        "IPAMConfig": null,
        "Links": null,
        "Aliases": null,
        "NetworkID": "689d6b65ce1b06c93b2c70f41760a3e7fb2b50697d71cd9c1f39c64c865e5fa6",
        "EndpointID": "76bf1f8638d1ff0387e6c3fe89e8ccab1670c709ad550f9acc6f46e559654bee",
        "Gateway": "172.17.0.1",
        "IPAddress": "172.17.0.3",
        "IPPrefixLen": 16
      }
    },
    "MacAddress": "02:42:ac:11:00:03",
    "SecondaryIPAddresses": null,
    "SandboxKey": "/var/run/docker/netns/24a031d9dfda",
    "Ports": {
      "0/tcp": null
    },
    "LinkLocalIPv6PrefixLen": 0,
    "LinkLocalIPv6Address": "",
    "HairpinMode": false,
    "SandboxID": "24a031d9dfda70026a875f4841269c5e790b12ccafcc11869111faa240020b99",
    "Bridge": "",
    "SecondaryIPv6Addresses": null,
    "EndpointID": "76bf1f8638d1ff0387e6c3fe89e8ccab1670c709ad550f9acc6f46e559654bee",
    "Gateway": "172.17.0.1",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "IPAddress": "172.17.0.3",
    "IPPrefixLen": 16,
    "IPv6Gateway": ""
  },

    },
    "AttachStderr": true,
    "AttachStdout": true,
    "AttachStdin": true,
    "User": "",
    "Domainname": "",
    "Hostname": "f5d3273e4835",
    "OpenStdin": true,
    "StdinOnce": true,
    "Env": [
      "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
    ],
    "Cmd": [
      "/bin/bash"
    ],
    "ArgsEscaped": true,
    "Image": "ubuntu:14.04",

<*************REMOVING THE OUTPUT CONTENT********>

  "ExecIDs": null,
  "HostnamePath": "/var/lib/docker/containers/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940/hostname",
  "ResolvConfPath": "/var/lib/docker/containers/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940/resolv.conf",
  "Image": "sha256:132b7427a3b40f958aaeae8716e0cbb2177658d2410554ed142e583ef522309f",
  "State": {
    "FinishedAt": "0001-01-01T00:00:00Z",
    "StartedAt": "2017-06-09T06:53:45.120357144Z",
    "Error": "",
    "Status": "running",
    "Running": true,
    "Paused": false,
    "Restarting": false,

  "Path": "/bin/bash",
  "Created": "2017-06-09T06:52:51.820429355Z",
  "Id": "f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940",
  "HostsPath": "/var/lib/docker/containers/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940/hosts",
  "LogPath": "/var/lib/docker/containers/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940/f5d3273e48350d606bd8b9d2a5bd876dc5c2d1a73183f876a1dd56473cad8940-json.log",
  "Name": "/objective_bartik",
  "RestartCount": 0,
  "Driver": "aufs",
  "MountLabel": "",
  "ProcessLabel": "",
  "AppArmorProfile": "docker-default"
}

Refer this for more info:

DOCKER APIs

How to build an Image using Docker API?

How to commit Docker Container using API

Hope this info will he helpful.


来源: stackexchange

问:
Can't get form button link to open in new window
I've build a small form button but somehow I can't get the link to open in a new tab. I've tried the target blank attribute but no results. I've also tried changing onclick="window.location.href to onclick="window.open.href but nothing seems to work.. Here is the HTML:

    <form>
<input style="width: 100%;
min-width: 50px;
max-width: 300px;
 padding: 20px;
 cursor: pointer;
 box-shadow: 6px 6px 5px; #999;
 -webkit-box-shadow: 6px 6px 5px #999;
 -moz-box-shadow: 6px 6px 5px #999;
 font-weight: bold;
 background: #9b5103;
 color: #000;
 border-radius: 2px;
 border: 1px solid #999;
 font-size: 150%;" type="button" value="Kayak Tarifa" onclick="window.location.href='https://stackoverflow.com/'" />
</form>

```

答:
Use onclick="window.open('https://stackoverflow.com/', '_blank');" instead

input {
  width: 100%;
  min-width: 50px;
  max-width: 300px;
  padding: 20px;
  cursor: pointer;
  box-shadow: 6px 6px 5px #999;
  -webkit-box-shadow: 6px 6px 5px #999;
  -moz-box-shadow: 6px 6px 5px #999;
  font-weight: bold;
  background: #9b5103;
  color: #000;
  border-radius: 2px;
  border: 1px solid #999;
  font-size: 150%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form target="_blank">
  <input style="" type="button" value="Kayak Tarifa" onclick="window.open('https://stackoverflow.com/', '_blank');" />
</form></code>```

ContentLicense: CC BY-SA 3.0

Body:
Use onclick="window.open('https://stackoverflow.com/', '_blank');" instead

input {
  width: 100%;
  min-width: 50px;
  max-width: 300px;
  padding: 20px;
  cursor: pointer;
  box-shadow: 6px 6px 5px #999;
  -webkit-box-shadow: 6px 6px 5px #999;
  -moz-box-shadow: 6px 6px 5px #999;
  font-weight: bold;
  background: #9b5103;
  color: #000;
  border-radius: 2px;
  border: 1px solid #999;
  font-size: 150%;
}

<form target="_blank">
  <input style="" type="button" value="Kayak Tarifa" onclick="window.open('https://stackoverflow.com/', '_blank');" />
</form>


问:
don't want whitespace to occur when text is too long and i got to enter
Is there any way when your text is too long - and you break it up with new lines - to not have whitespace happen? What I need is three values to be joint without whitespace in between.

```<code><div style='font-size:100%; color:blue'>
    {{ $record->m_pk_address_line1 }}
    {{ $record->m_pk_address_line2 }}
    {{ $record->m_pk_address_line3 }}
</div>
</code>```

Without entering new line, it'll be too long even if they can be joined together.

```<code><div style='font-size:100%; color:blue'>{{ $record->m_pk_address_line1 }}{{ $record->m_pk_address_line2 }}{{ $record->m_pk_address_line3 }}</div>
</code>```

Is there no standard way of going about this without resorting to tricks? What do people do when their code is too long and they need to break it up into new lines but they don't want the whitespace that comes with it?

答:
For removing whitespaces use</p>

```<code>$string= preg_replace('/\s+/', '', $string);

<div style='font-size:100%; color:blue'>
    {{ preg_replace('/\s+/', '', $record->m_pk_address_line1 }}
    {{ preg_replace('/\s+/', '', $record->m_pk_address_line1 }}
    {{ preg_replace('/\s+/', '', $record->m_pk_address_line1 }}
</div>
</code>```

Body:
Is there any way when your text is too long - and you break it up with new lines - to not have whitespace happen? What I need is three values to be joint without whitespace in between.

    {{ $record->m_pk_address_line1 }}
    {{ $record->m_pk_address_line2 }}
    {{ $record->m_pk_address_line3 }}

Without entering new line, it'll be too long even if they can be joined together.

{{ $record->m_pk_address_line1 }}{{ $record->m_pk_address_line2 }}{{ $record->m_pk_address_line3 }}

Is there no standard way of going about this without resorting to tricks? What do people do when their code is too long and they need to break it up into new lines but they don't want the whitespace that comes with it?

Body:
For removing whitespaces use

$string= preg_replace('/\s+/', '', $string);

<div style='font-size:100%; color:blue'>
    {{ preg_replace('/\s+/', '', $record->m_pk_address_line1 }}
    {{ preg_replace('/\s+/', '', $record->m_pk_address_line1 }}
    {{ preg_replace('/\s+/', '', $record->m_pk_address_line1 }}
</div>


问:
No bash shell generated from ExecV
I'm trying to learn about buffer overflows on my Ubuntu 12.04 32 bit machine by following along with the videos at http://www.securitytube.net/groups?operation=view&groupId=4 . Currently, I'm on part 5, which injects some relocatable code to generate a bash shell via ExecVe

I can get the Shellcode.c to build just fine, using gcc -mpreferred-stack-boundary=2 -o Shellcode Shellcode.c as it shows in the part 5 video. However, when I run the C code, all I get is Segmentation Fault (core dumped). I do not get a bash shell spawned like it shows in the video.

Can anyone tell me why I'm not spawning a bash shell like the demo shows? My gut is telling me that this is because I am using a later version kernel (no idea what is used in the demo).

Thanks!

code follows:

```<code>Shellcode.c

#include<stdio.h>

char shellcode[] = "\xeb\x18\x5e\x31\xc0\x88\x46\x09\x89\x76\x0a"
                   "\x89\x46\x0e\xb0\x0b\x89\xf3\x8d\x4e\x0a\x8d\x56\x0e"
                   "\xcd\x80\xe8\xe3\xff\xff\xff\x2f\x62\x69\x6e\x2f\x62"
                   "\x61\x73\x68\x41\x42\x42\x42\x42\x43\x43\x43\x43";

int main(){

        int *ret;

        ret = (int *)&ret +2;

        (*ret) = (int)shellcode;

}
</code>```

答:
My friend,
make sure you compile it correctly.

If it is 32bits shellcode, which is very likely becasue \xcd\x80 is there.

And make sure the stack is executable and no stack protector is there

gcc -m32 -o a shell.code -fno-stack-protector -z execstack
./a

This should give you a shell if your shellcode is right.

If not run gdb a to step through which part is wrong.

Title: No bash shell generated from ExecV

Body:
I'm trying to learn about buffer overflows on my Ubuntu 12.04 32 bit machine by following along with the videos at http://www.securitytube.net/groups?operation=view&groupId=4 . Currently, I'm on part 5, which injects some relocatable code to generate a bash shell via ExecVe

I can get the Shellcode.c to build just fine, using gcc -mpreferred-stack-boundary=2 -o Shellcode Shellcode.c as it shows in the part 5 video. However, when I run the C code, all I get is Segmentation Fault (core dumped). I do not get a bash shell spawned like it shows in the video.

Can anyone tell me why I'm not spawning a bash shell like the demo shows? My gut is telling me that this is because I am using a later version kernel (no idea what is used in the demo).

Thanks!

code follows:

Shellcode.c

#include<stdio.h>

char shellcode[] = "\xeb\x18\x5e\x31\xc0\x88\x46\x09\x89\x76\x0a"
                   "\x89\x46\x0e\xb0\x0b\x89\xf3\x8d\x4e\x0a\x8d\x56\x0e"
                   "\xcd\x80\xe8\xe3\xff\xff\xff\x2f\x62\x69\x6e\x2f\x62"
                   "\x61\x73\x68\x41\x42\x42\x42\x42\x43\x43\x43\x43";

int main(){

        int *ret;

        ret = (int *)&ret +2;

        (*ret) = (int)shellcode;

}


问:
C# enum query linq and general type?
So I want to know that, from my enum value list, how many specific enum value exists.

So I wrote like

```<code>public int GetNumFromList(List<Elements> list, Elements eType)
{
    IEnumerable<Elements> query = //list.Where(p => p.GetType() == eType);
        from listchild in list
        where listchild == eType
        select listchild;
    /*
    Debug.Log("Cur check type is " + eType + " and now selected number is " + query.Count());
    if(query.Count() > 0)
        Debug.Log(" and query 0 value is "+ query.ToArray().GetValue(0) + " type is "+ query.ToArray().GetValue(0).GetType());
        */
    return query.Count();
}
  public enum Elements{Fire, Water, Wood, Metal, Earth, None}
</code>```

So this works well, but can I make this more shorter and neat?

```<code>//list.Where(p => p.GetType() == eType);  This part doesn't worked.
</code>```

And how can make this for generic type, T?

答:
Try this: </p>

```<code>IEnumerable<Elements> query = list.Where(p => p == eType);
</code>```

Title: C# enum query linq and general type?

Body:
So I want to know that, from my enum value list, how many specific enum value exists.

So I wrote like

public int GetNumFromList(List<Elements> list, Elements eType)
{
    IEnumerable<Elements> query = //list.Where(p => p.GetType() == eType);
        from listchild in list
        where listchild == eType
        select listchild;
    /*
    Debug.Log("Cur check type is " + eType + " and now selected number is " + query.Count());
    if(query.Count() > 0)
        Debug.Log(" and query 0 value is "+ query.ToArray().GetValue(0) + " type is "+ query.ToArray().GetValue(0).GetType());
        */
    return query.Count();
}
  public enum Elements{Fire, Water, Wood, Metal, Earth, None}

So this works well, but can I make this more shorter and neat?

//list.Where(p => p.GetType() == eType);  This part doesn't worked.

And how can make this for generic type, T?

Body:
Try this:

IEnumerable<Elements> query = list.Where(p => p == eType);


问:
Deployment angularjs Application on server
I have developed a web application using angualrjs and MVC . this application is working fine at my local end but after deploying on server . angularjs is not working . I think server is unable to load angularjs library

Now i need help to eliminate this behavior of my web application.

For reference i am attaching an Image

Reference Image

答:
I use firebase to deploy my Angular apps. It's free.
https://firebase.google.com/</p>


问:
Difference between TestCase and TransactionTestCase classes in django test
Please explain the difference between the TestCase class and TransactionTestCase class. I have read the documentation but it's only saying that TestCase runs tests in a database transaction and uses rollback to "undo" the test in the database, and if you need to manually manage transactions within your test, you would need to use django.test.TransactionTestCase.

Please help me understand the actual difference with an example.
In what condition will TestCase fail? Do rollbacks happen automatically or do we have to write code to do the rollback?

答:
The main difference between TestCase and TransactionTestCase is that TestCase wraps the tests with atomic() blocks ALL THE TIME. From the documentation:

Wraps the tests within two nested atomic() blocks: one for the whole class and one for each test

Now imagine that you have a method that should raise an error if it is not wrapped inside atomic() block. You are trying to write a test for that:

```<code>def test_your_method_raises_error_without_atomic_block(self):
    with self.assertRaises(SomeError):
        your_method()
</code>```

This test will unexpectedly fail! The reason is, you guessed it, TestCase wraps the tests with atomic() blocks ALL THE TIME. Thus, your_method() will not raise an error, which is why this test will fail. In this case, you should use TransactionTestCase to make your test pass.

select_for_update() is a clear case in point:

Evaluating a queryset with select_for_update() in autocommit mode on backends which support SELECT ... FOR UPDATE is a TransactionManagementError error

From the TransactionTestCase documentation:

with TestCase class, you cannot test that a block of code is executing within a transaction, as is required when using select_for_update()

And if we take a look at the documentation of select_for_update(), we see a warning:

Although select_for_update() normally fails in autocommit mode, since TestCase automatically wraps each test in a transaction, calling select_for_update() in a TestCase even outside an atomic() block will (perhaps unexpectedly) pass without raising a TransactionManagementError. To properly test select_for_update() you should use TransactionTestCase.

Hope it helps!

ContentLicense: CC BY-SA 4.0

Body:
The main difference between TestCase and TransactionTestCase is that TestCase wraps the tests with atomic() blocks ALL THE TIME. From the documentation:

Wraps the tests within two nested atomic() blocks: one for the whole class and one for each test

Now imagine that you have a method that should raise an error if it is not wrapped inside atomic() block. You are trying to write a test for that:

def test_your_method_raises_error_without_atomic_block(self):
    with self.assertRaises(SomeError):
        your_method()

This test will unexpectedly fail! The reason is, you guessed it, TestCase wraps the tests with atomic() blocks ALL THE TIME. Thus, your_method() will not raise an error, which is why this test will fail. In this case, you should use TransactionTestCase to make your test pass.

select_for_update() is a clear case in point:

Evaluating a queryset with select_for_update() in autocommit mode on backends which support SELECT ... FOR UPDATE is a TransactionManagementError error

From the TransactionTestCase documentation:

with TestCase class, you cannot test that a block of code is executing within a transaction, as is required when using select_for_update()

And if we take a look at the documentation of select_for_update(), we see a warning:

Although select_for_update() normally fails in autocommit mode, since TestCase automatically wraps each test in a transaction, calling select_for_update() in a TestCase even outside an atomic() block will (perhaps unexpectedly) pass without raising a TransactionManagementError. To properly test select_for_update() you should use TransactionTestCase.

Hope it helps!


问:
split string and store it in another variable in c#
How to Read character after '\':

```<code>string PrName = "software\Plan Mobile";
</code>```

答:
First of all, do not forget @:

```<code> string PrName = @"software\Plan Mobile";
</code>```

Next, if you want just the tail only (i.e. "Plan Mobile") then Substring will do:

```<code> // if no '\' found, the entire string will be return
 string tail = PrName.Substring(PrName.IndexOf('\\') + 1);
</code>```

If you want both (all parts), try Split:

```<code> // parts[0] == "software"
 // parts[1] == "Plan Mobile"
 string[] parts = PrName.Split('\\');
</code>```

Body:
How to Read character after '\':

string PrName = "software\Plan Mobile";

Body:
First of all, do not forget @:

 string PrName = @"software\Plan Mobile";

Next, if you want just the tail only (i.e. "Plan Mobile") then Substring will do:

 // if no '\' found, the entire string will be return
 string tail = PrName.Substring(PrName.IndexOf('\\') + 1);

If you want both (all parts), try Split:

 // parts[0] == "software"
 // parts[1] == "Plan Mobile"
 string[] parts = PrName.Split('\\');


答:
You could make an accessor in the model of $record

```<code>public function getFullAddressAttribute($value)
{
    return $record->m_pk_address_line1 . $record->m_pk_address_line2 . $record->m_pk_address_line3;
}
</code>```

and use that in your views like this

```<code>$record->full_address;
</code>```

Title: don't want whitespace to occur when text is too long and i got to enter

Body:
You could make an accessor in the model of $record

public function getFullAddressAttribute($value)
{
    return $record->m_pk_address_line1 . $record->m_pk_address_line2 . $record->m_pk_address_line3;
}

and use that in your views like this

$record->full_address;


问:
ES6 - Warning: setState(…): Cannot update during an existing state transition
I am rewriting some old ReactJS code, and got stuck fixing this error (the error repeats about 1700 times in the console, the DOM does not render at all):

Warning: setState(...): Cannot update during an existing state
  transition (such as within render or another component's
  constructor). Render methods should be a pure function of props and
  state; constructor side-effects are an anti-pattern, but can be moved
  to componentWillMount.

I am a Component that passes it's state down to a component that should render some controls. Based on the clicked controls, the state should change, and new controls should render.

So this is my Container component:

```<code>class TeaTimer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 120,
            countdownStatus: 'started'
        }
    }

    componentDidUpdate(prevProps, prevState) {
        if (this.state.countdownStatus !== prevState.countdownStatus) {
            switch (this.state.countdownStatus) {
                case 'started':
                    this.startTimer();
                    break;
                case 'stopped':
                    this.setState({count:0});
            }
        }
    }

    componentWillUnmount() {
        clearInterval(this.timer);
        delete this.timer;
    }

    startTimer() {
        this.timer = setInterval(() => {
            let newCount = this.state.count -1;
            this.setState({
                count: newCount >= 0 ? newCount : 0
            });
            if(newCount === 0) {
                this.setState({countdownStatus: 'stopped'});
            }
        }, 1000)
    }

    handleStatusChange(newStatus) {
        this.setState({ countdownStatus: newStatus });
    }

    render() {
        let {count, countdownStatus} = this.state;
        let renderStartStop = () => {
            if (countdownStatus !== 'stopped') {
                return <StartStop countdownStatus={countdownStatus} onStatusChange={this.handleStatusChange()}/>
            } else {
                return <div>This will be the slider form</div>
            }
        };
        return(
            <div className={styles.container}>
                <p>This is the TeaTimer component</p>
                <Clock totalSeconds={count}/>
                {renderStartStop()}
            </div>
        )
    }
}
</code>```

And this is my controls component:

```<code>class StartStop extends Component {
    constructor(props) {
        super(props);
    }

    onStatusChange(newStatus) {
        return() => {
            this.props.onStatusChange(newStatus);
        }
    }

    render() {
        let {countdownStatus} = this.props;

        let renderStartStopButton = () => {
            if(countdownStatus === 'started') {
                return <button onClick={()=> this.onStatusChange('stopped')}>Reset</button>;
            } else {
                return <button onClick={()=> this.onStatusChange('started')}>Start</button>
            }
        };

        return(
            <div className={styles.tt.Controls}>
                {renderStartStopButton()}
            </div>
        )
    }
}

StartStop.propTypes = {
    countdownStatus: React.PropTypes.string.isRequired,
    onStatusChange: React.PropTypes.func.isRequired
};
</code>```

I am sorry about the wall of text, but I really can;t figure out where the error is coming from - and therefor don't know which part of the code I can leave out.

I have tried implementing the solution found in a seemingly related question, but can't get it to work either.

答:
Your metods call each other so you must define two instance of your metods. </p>

```<code>class StartStop extends Component {
    constructor(props) {
        super(props);
        this.onStatusChangeReset=this.onStatusChange.bind(this);
        this.onStatusChangeStart=this.onStatusChange.bind(this);

    }

    onStatusChange(newStatus) {
        return() => {
            this.props.onStatusChange(newStatus);
        }
    }

    render() {
        let {countdownStatus} = this.props;

        let renderStartStopButton = () => {
            if(countdownStatus === 'started') {
                return <button onClick={this.onStatusChangeReset('stopped')}>Reset</button>;
            } else {
                return <button onClick={this.onStatusChangeStart('started')}>Start</button>
            }
        };

        return(
            <div className={styles.tt.Controls}>
                {renderStartStopButton()}
            </div>
        )
    }
}

StartStop.propTypes = {
    countdownStatus: React.PropTypes.string.isRequired,
    onStatusChange: React.PropTypes.func.isRequired
};
</code>```

Body:
I am rewriting some old ReactJS code, and got stuck fixing this error (the error repeats about 1700 times in the console, the DOM does not render at all):

Warning: setState(...): Cannot update during an existing state
  transition (such as within render or another component's
  constructor). Render methods should be a pure function of props and
  state; constructor side-effects are an anti-pattern, but can be moved
  to componentWillMount.

I am a Component that passes it's state down to a component that should render some controls. Based on the clicked controls, the state should change, and new controls should render.

So this is my Container component:

class TeaTimer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 120,
            countdownStatus: 'started'
        }
    }

    componentDidUpdate(prevProps, prevState) {
        if (this.state.countdownStatus !== prevState.countdownStatus) {
            switch (this.state.countdownStatus) {
                case 'started':
                    this.startTimer();
                    break;
                case 'stopped':
                    this.setState({count:0});
            }
        }
    }

    componentWillUnmount() {
        clearInterval(this.timer);
        delete this.timer;
    }

    startTimer() {
        this.timer = setInterval(() => {
            let newCount = this.state.count -1;
            this.setState({
                count: newCount >= 0 ? newCount : 0
            });
            if(newCount === 0) {
                this.setState({countdownStatus: 'stopped'});
            }
        }, 1000)
    }

    handleStatusChange(newStatus) {
        this.setState({ countdownStatus: newStatus });
    }

    render() {
        let {count, countdownStatus} = this.state;
        let renderStartStop = () => {
            if (countdownStatus !== 'stopped') {
                return <StartStop countdownStatus={countdownStatus} onStatusChange={this.handleStatusChange()}/>
            } else {
                return
This will be the slider form

            }
        };
        return(

This is the TeaTimer component

                <Clock totalSeconds={count}/>
                {renderStartStop()}

        )
    }
}

And this is my controls component:

class StartStop extends Component {
    constructor(props) {
        super(props);
    }

    onStatusChange(newStatus) {
        return() => {
            this.props.onStatusChange(newStatus);
        }
    }

    render() {
        let {countdownStatus} = this.props;

        let renderStartStopButton = () => {
            if(countdownStatus === 'started') {
                return <button onClick={()=> this.onStatusChange('stopped')}>Reset</button>;
            } else {
                return <button onClick={()=> this.onStatusChange('started')}>Start</button>
            }
        };

        return(

                {renderStartStopButton()}

        )
    }
}

StartStop.propTypes = {
    countdownStatus: React.PropTypes.string.isRequired,
    onStatusChange: React.PropTypes.func.isRequired
};

I am sorry about the wall of text, but I really can;t figure out where the error is coming from - and therefor don't know which part of the code I can leave out.

I have tried implementing the solution found in a seemingly related question, but can't get it to work either.

Body:
Your metods call each other so you must define two instance of your metods.

class StartStop extends Component {
    constructor(props) {
        super(props);
        this.onStatusChangeReset=this.onStatusChange.bind(this);
        this.onStatusChangeStart=this.onStatusChange.bind(this);

    }

    onStatusChange(newStatus) {
        return() => {
            this.props.onStatusChange(newStatus);
        }
    }

    render() {
        let {countdownStatus} = this.props;

        let renderStartStopButton = () => {
            if(countdownStatus === 'started') {
                return <button onClick={this.onStatusChangeReset('stopped')}>Reset</button>;
            } else {
                return <button onClick={this.onStatusChangeStart('started')}>Start</button>
            }
        };

        return(
            <div className={styles.tt.Controls}>
                {renderStartStopButton()}
            </div>
        )
    }
}

StartStop.propTypes = {
    countdownStatus: React.PropTypes.string.isRequired,
    onStatusChange: React.PropTypes.func.isRequired
};


问:
Count Values associated with key in Sql Server
I have three tables

Table Category

```<code>CategoryID         Category
1                   Climate
2                   Area
</code>```

Table CategoryDetail

```<code>DetailID    CategoryID      Desc
1            1              Hot
2            1              Cold
3            2              Area1
</code>```

Table CategoryDetailValues

```<code>PK  AnotherFK  CategoryDetailID
1    1           1
2    1           1
3    1           2
4    2           1
</code>```

Here AnotherFK is foreign key referring to another table. In record 1 and 2 duplicate exists that's ok but AnotherFK 1 has reference of CategoryDetailID 1 and 2 which has categoryID of 1 which is not ok

So from above tables
this result is valid from above three table

```<code>PK   AnotherFK    CategoryID  DetailID     Desc
1    1             1            1          Hot
2    1             1            1          Hot
</code>```

But below result is not valid

```<code>PK   AnotherFK    CategoryID  DetailID     Desc
2    1             1           1           Hot
3    1             1           2           Cold
</code>```

I can not put same AnotherFK in two different DetailID which has same CategoryID. I could have eliminated this by introducing CategoryID in CategoryDetailValues table and creating unique constraint but I am not allowed to do so.

Now my aim is to find all those record in CategoryDetailValues table which has different DetailID that are associated with same CategoryID. So that I can delete them.

Trying to achieve this in SQL Server 2012.

答:
If your goal is to highlight all AnotherFK cases that have the same CategoryID, but differenty DetailIDs, the following ought to do the trick (pseudo-code):

```<code>SELECT * FROM (SELECT AnotherFK, ROW_NUMBER() OVER
    (ORDER BY AnotherFK, CategoryID) AS rn FROM #myTable) AS a
WHERE rn > 1
</code>```

Sample code:

```<code>CREATE TABLE #myTable
(
  AnotherFK int
  , CategoryID int
  , DetailID int
  ) ;

  INSERT INTO #myTable (
  AnotherFK
  , CategoryID
  , DetailID
  )
  VALUES (1, 1, 1)
  ,  (1, 1, 2);

  SELECT * FROM (SELECT AnotherFK, ROW_NUMBER() OVER (ORDER BY AnotherFK, CategoryID) AS rn FROM #myTable) AS a
  WHERE rn > 1

  DROP TABLE #myTable
</code>```

If this is not what you are after, please elaborate

Body:
I have three tables

Table Category

CategoryID         Category
1                   Climate
2                   Area

Table CategoryDetail

DetailID    CategoryID      Desc
1            1              Hot
2            1              Cold
3            2              Area1

Table CategoryDetailValues

PK  AnotherFK  CategoryDetailID
1    1           1
2    1           1
3    1           2
4    2           1

Here AnotherFK is foreign key referring to another table. In record 1 and 2 duplicate exists that's ok but AnotherFK 1 has reference of CategoryDetailID 1 and 2 which has categoryID of 1 which is not ok

So from above tables
this result is valid from above three table

PK   AnotherFK    CategoryID  DetailID     Desc
1    1             1            1          Hot
2    1             1            1          Hot

But below result is not valid

PK   AnotherFK    CategoryID  DetailID     Desc
2    1             1           1           Hot
3    1             1           2           Cold

I can not put same AnotherFK in two different DetailID which has same CategoryID. I could have eliminated this by introducing CategoryID in CategoryDetailValues table and creating unique constraint but I am not allowed to do so.

Now my aim is to find all those record in CategoryDetailValues table which has different DetailID that are associated with same CategoryID. So that I can delete them.

Trying to achieve this in SQL Server 2012.

Body:
If your goal is to highlight all AnotherFK cases that have the same CategoryID, but differenty DetailIDs, the following ought to do the trick (pseudo-code):

SELECT * FROM (SELECT AnotherFK, ROW_NUMBER() OVER
    (ORDER BY AnotherFK, CategoryID) AS rn FROM #myTable) AS a
WHERE rn > 1

Sample code:

CREATE TABLE #myTable
(
  AnotherFK int
  , CategoryID int
  , DetailID int
  ) ;

  INSERT INTO #myTable (
  AnotherFK
  , CategoryID
  , DetailID
  )
  VALUES (1, 1, 1)
  ,  (1, 1, 2);

  SELECT * FROM (SELECT AnotherFK, ROW_NUMBER() OVER (ORDER BY AnotherFK, CategoryID) AS rn FROM #myTable) AS a
  WHERE rn > 1

  DROP TABLE #myTable

If this is not what you are after, please elaborate


问:
What is a fractal?
Duplicate of How to program a fractal

What are fractals?

Is this is one of the concepts that is brought over from Mathematics to programming to simplify or solve a particular set of problems?

 I am closing this question and have posted a related  question

答:
A fractal is generally "a rough or fragmented geometric shape that can be split into parts, each of which is (at least approximately) a reduced-size copy of the whole," a property called self-similarity. The term was coined by Benoît Mandelbrot in 1975 and was derived from the Latin fractus meaning "broken" or "fractured." A mathematical fractal is based on an equation that undergoes iteration, a form of feedback based on recursion.

A fractal often has the following features:

It has a fine structure at arbitrarily small scales.

It is too irregular to be easily described in traditional Euclidean geometric language.

It is self-similar (at least approximately or stochastically).

It has a Hausdorff dimension which is greater than its topological dimension (although this requirement is not met by space-filling curves such as the Hilbert curve).

It has a simple and recursive definition.

http://en.wikipedia.org/wiki/Fractal

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5

Title: What is a fractal?

LastEditorDisplayName: Nick

OwnerDisplayName: Rich B


问:
toJson method causing UI to freeze
I have an ArrayList of objects that I am saving to SharedPreferences in my Activities onPause method. When I try to serialize it to json, I get the following in the logs (these 2 statements repeat and overload the logcat) :

```<code>06-20 20:33:31.620  26245-26252/com.example.app W/art﹕ Suspending all threads took: 21.556ms
06-20 20:33:31.620  26245-26260/com.example.app W/art﹕ Suspending all threads took: 5.901ms
06-20 20:33:31.650  26245-26260/com.example.app I/art﹕ Background partial concurrent mark sweep GC freed 210493(6MB) AllocSpace objects, 87(2MB) LOS objects, 25% free, 47MB/63MB, paused 16.970ms total 155.761ms
06-20 20:33:32.480  26245-26260/com.example.app I/art﹕ Background sticky concurrent mark sweep GC freed 346396(10MB) AllocSpace objects, 140(4MB) LOS objects, 14% free, 48MB/56MB, paused 13ms total 88.199ms
</code>```

I initialize the ArrayList in onCreate and then give it the objects when I am done executing an Asynctask. Here is the problem method that causes the UI to freeze:

```<code>  @Override
  protected void onPause() {
  super.onPause();
  String json = mGson.toJson(mSelectedContactList);
  mSharedPreferences.edit().putString("contact_list", json).apply();
  }
</code>```

I have also tried the following and continue to get the freeze up:

```<code>    JsonElement element =
    mGson.toJsonTree(mSelectedContactList, new TypeToken<ArrayList<ContactObject>>() {
    }.getType());
    String jsonString = element.getAsJsonArray().getAsString();
</code>```

I know it is not the SharedPreferences that is the problem. I suspect the toJson method can't handle the process but I cannot figure out what is the problem here. Any help will be much appreciated.

*EDIT: Here is the class that I am using:

```<code>public class ContactObject implements Parcelable {

// Instance variables
private String mID;
private String mNumber;
private String mName;
private boolean mHasPhoto;
private ArrayMap<Long, InboxSmsObject> mSentMessages;
private ArrayMap<Long, OutboxSmsObject> mReceivedMessages;
...
}
</code>```

答: If you have a constructor for ContactObject just remove it. It should work fine afterwards.</p>

Title: toJson method causing UI to freeze

Body:
I have an ArrayList of objects that I am saving to SharedPreferences in my Activities onPause method. When I try to serialize it to json, I get the following in the logs (these 2 statements repeat and overload the logcat) :

06-20 20:33:31.620  26245-26252/com.example.app W/art﹕ Suspending all threads took: 21.556ms
06-20 20:33:31.620  26245-26260/com.example.app W/art﹕ Suspending all threads took: 5.901ms
06-20 20:33:31.650  26245-26260/com.example.app I/art﹕ Background partial concurrent mark sweep GC freed 210493(6MB) AllocSpace objects, 87(2MB) LOS objects, 25% free, 47MB/63MB, paused 16.970ms total 155.761ms
06-20 20:33:32.480  26245-26260/com.example.app I/art﹕ Background sticky concurrent mark sweep GC freed 346396(10MB) AllocSpace objects, 140(4MB) LOS objects, 14% free, 48MB/56MB, paused 13ms total 88.199ms

I initialize the ArrayList in onCreate and then give it the objects when I am done executing an Asynctask. Here is the problem method that causes the UI to freeze:

  @Override
  protected void onPause() {
  super.onPause();
  String json = mGson.toJson(mSelectedContactList);
  mSharedPreferences.edit().putString("contact_list", json).apply();
  }

I have also tried the following and continue to get the freeze up:

    JsonElement element =
    mGson.toJsonTree(mSelectedContactList, new TypeToken<ArrayList<ContactObject>>() {
    }.getType());
    String jsonString = element.getAsJsonArray().getAsString();

I know it is not the SharedPreferences that is the problem. I suspect the toJson method can't handle the process but I cannot figure out what is the problem here. Any help will be much appreciated.

*EDIT: Here is the class that I am using:

public class ContactObject implements Parcelable {

// Instance variables
private String mID;
private String mNumber;
private String mName;
private boolean mHasPhoto;
private ArrayMap<Long, InboxSmsObject> mSentMessages;
private ArrayMap<Long, OutboxSmsObject> mReceivedMessages;
...
}


问:
Multiple errors while sending message on Moodle
I'm stuck with this problem for some time now: Moodle (an LMS template) should automatically send e-mail students about every little change in their courses, like new messages on foruns, new homework added, new file uploaded, etc - but it never does. We tried everything. We set and reset the Email configurations, reinstalled Moodle, updated it, changed PHP version, changed and rechanged the CRON execution time (30s, 1min, 5min - we tried all common settings) and nothing seems to make the smallest difference. With this new update, Moodle is now giving some hint of what the problem should be: we tested a new setting, tried to send an email to a couple of students and here's the erros messages it printed:

Error Messages:

Note that this didn't show before. And at any rate, it's as good as nothing, since we don't have any clue what Moodle is expecting us to do.

Our SMTP settings on Moodle:

settings screenshot 1

settings screenshot 2

We are using PHP version 5.6 for our moodle website and the Moodle's version is 3.3

Can you guys shed some light on this matter? We's appreciate a little help, thanks a lot!

PS.: I am aware that there are other threads on this, but, since most of them are directed to people that actually own a server (wich we don't - our site is hosted on a third party web hosting) and none of them solved our issue, I'm opening a new thread on this.

答:
Have you had a look at this page of the documentation?

https://docs.moodle.org/33/en/Email_setup_gmail

It looks like you're selecting the wrong Security parameter.


问:
Pass variables to template
im using NodeJS/Expressjs and I have this route:

```<code>router.post({

   var value = req.body.value;
   //I NEED TO DO SOMETHING LIKE
   var file = '../test/test.js';
   file.render(value);

});
</code>```

and /test/test.js looks like

```<code>var myVar = {value1};
var someStruct = {key: {value2}}
function Test(){
  var info = {value3};
}
</code>```

Which is the good way to do this?
Can I use some templating system?

Regards,

答:
Have a look into the EJS templating system. Does what you are asking.</p>

```<code>// server.js
// load the things we need
var express = require('express');
var app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');

// pass and object/string into the render function as the second arg.
app.post('/your-url', function(req, res) {
    let data = {
        object: 'string'
    };
    res.render('pages/index', data);
});

app.listen(8080);
console.log('8080 is the magic port');
</code>```

Title: Pass variables to template

Body:
im using NodeJS/Expressjs and I have this route:

router.post({

   var value = req.body.value;
   //I NEED TO DO SOMETHING LIKE
   var file = '../test/test.js';
   file.render(value);

});

and /test/test.js looks like

var myVar = {value1};
var someStruct = {key: {value2}}
function Test(){
  var info = {value3};
}

Which is the good way to do this?
Can I use some templating system?

Regards,

Body:
Have a look into the EJS templating system. Does what you are asking.

// server.js
// load the things we need
var express = require('express');
var app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');

// pass and object/string into the render function as the second arg.
app.post('/your-url', function(req, res) {
    let data = {
        object: 'string'
    };
    res.render('pages/index', data);
});

app.listen(8080);
console.log('8080 is the magic port');


问:
Where does Visual Studio store the watch window data?
I use to have some complex expressions in the watch window and out of a sudden the watch window is completely empty now. Of course I can put the expressions back manually but it would be really interesting to know where Visual Studio stores the watch window data? I doubt that it's stored in some solution related file since after a clean build the watches are still there.

I am using Visual Studio 2013 on Windows 10.

答:
Watch window information is stored in the .suo file for the solution. I couldnt find it in any of the official documentation for, but the breakpoints are there and if you configure the watch window, then close VS, then delete the .suo file and open VS the watch window is empty. After closing VS, restoring the .suo file and opening VS again the watch window configuration is back. This is confirmed for instance by this blog post:

What informations are saved in my .suo file

This file is used by Visual Studio to store user/solution specific
  information such as Opened Files, Expanded Nodes in the Solution
  Visual Studio .suo fileExplorer, Opened Tool Windows and its
  Positions, User Tasks, Breakpoints, Start-up Project, Contents of
  Watch window, Whether the project is loaded/unloaded  etc. The same
  file is used by Visual Studio Addins (VSPackages) to persist
  information that are specific to that solution/user.

I don't know where your .suo file went though, did you accidentally delete it?


问:
CUDA Programming adding vectors in parallel is much slower(not faster)
I am a beginner in CUDA programming. I am trying to measure how efficient adding vectors in parallel is. However, I've realized that it's actually much slower than adding vectors not in parallel, which is the opposite of what I expected. I do not understand why this happens. Adding in parallel took 2904763 nano seconds and not adding in parallel took only 340 nano seconds. Please explain why. </p>

```<code>#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <chrono>
cudaError_t addWithCuda(int *c, const int *a, const int *b, unsigned int size);

__global__ void addKernel(int *c, const int *a, const int *b)
{
    int i = threadIdx.x;
    c[i] = a[i] * b[i];
}

// randomize array with random numbers
void randomizeArr(int arr[],  int size) {

    unsigned int randNum;
    srand(time(NULL));
    for (int i = 0; i < size; i++) {
        randNum = rand() % 100 + 1;
        arr[i] = randNum;
    }
}

void addWithCPU(int c[], int a[], int b[], int size) {
    for (int i = 0; i < size; i++) {
        c[i] = a[i] + b[i];
    }
}

int main()
{
    const int arSize = 100;
    int a[arSize] = { 0 };
    int b[arSize] = { 0 };
    randomizeArr(a, arSize);
    randomizeArr(b, arSize);
    int c[arSize] = { 0 };
    int d[arSize] = { 0 };

    // Add vectors in parallel.
    int iterations = 100;
    cudaError cudaStatus;
    auto begin = std::chrono::high_resolution_clock::now();
    for (uint32_t i = 0; i < iterations; ++i)
    {
        cudaStatus = addWithCuda(c, a, b, arSize);
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count();
    std::cout << "Parallel : " << duration / iterations << "ns." << std::endl;

    // Add vectors NOT in parallel.
    auto begin2 = std::chrono::high_resolution_clock::now();
    for (uint32_t i = 0; i < iterations; ++i)
    {
        addWithCPU(d, a, b, arSize);
    }
    auto end2 = std::chrono::high_resolution_clock::now();
    auto duration2 = std::chrono::duration_cast<std::chrono::nanoseconds>(end2 - begin2).count();
    std::cout << "Not Parallel : " << duration2 / iterations << "ns." << std::endl;

    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "addWithCuda failed!");
        fprintf( stderr ,"HERREEEE");
        std::getchar();
        return 1;
    }

    // cudaDeviceReset must be called before exiting in order for profiling and
    // tracing tools such as Nsight and Visual Profiler to show complete traces.
    cudaStatus = cudaDeviceReset();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaDeviceReset failed!");
        return 1;
    }
    std::getchar();

    return 0;
}

// Helper function for using CUDA to add vectors in parallel.
cudaError_t addWithCuda(int *c, const int *a, const int *b, unsigned int size)
{
    int *dev_a = 0;
    int *dev_b = 0;
    int *dev_c = 0;
    cudaError_t cudaStatus;

    // Choose which GPU to run on, change this on a multi-GPU system.
    cudaStatus = cudaSetDevice(0);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaSetDevice failed!  Do you have a CUDA-capable GPU installed?");
        goto Error;
    }

    // Allocate GPU buffers for three vectors (two input, one output)    .
    cudaStatus = cudaMalloc((void**)&dev_c, size * sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&dev_a, size * sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&dev_b, size * sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    // Copy input vectors from host memory to GPU buffers.
    cudaStatus = cudaMemcpy(dev_a, a, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

    cudaStatus = cudaMemcpy(dev_b, b, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

    // Launch a kernel on the GPU with one thread for each element.
    addKernel<<<1, size>>>(dev_c, dev_a, dev_b);

    // Check for any errors launching the kernel
    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "addKernel launch failed: %s\n", cudaGetErrorString(cudaStatus));
        goto Error;
    }

    // cudaDeviceSynchronize waits for the kernel to finish, and returns
    // any errors encountered during the launch.
    cudaStatus = cudaDeviceSynchronize();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus);
        goto Error;
    }

    // Copy output vector from GPU buffer to host memory.
    cudaStatus = cudaMemcpy(c, dev_c, size * sizeof(int), cudaMemcpyDeviceToHost);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

Error:
    cudaFree(dev_c);
    cudaFree(dev_a);
    cudaFree(dev_b);

    return cudaStatus;
}
</code>```

答:
For a small set of value you will be slower because :

you need you copy your buffer on the device memory

you need to perform the computations

you need to copy the device buffer back on the host memory

Copying the data to device and back to the host are very costful operations. If you test your code on a much larger dataset, you should have a much larger increase factor of performance.

Try with 100 000 numbers.

Body:
I am a beginner in CUDA programming. I am trying to measure how efficient adding vectors in parallel is. However, I've realized that it's actually much slower than adding vectors not in parallel, which is the opposite of what I expected. I do not understand why this happens. Adding in parallel took 2904763 nano seconds and not adding in parallel took only 340 nano seconds. Please explain why.

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <chrono>
cudaError_t addWithCuda(int *c, const int *a, const int *b, unsigned int size);

__global__ void addKernel(int *c, const int *a, const int *b)
{
    int i = threadIdx.x;
    c[i] = a[i] * b[i];
}

// randomize array with random numbers
void randomizeArr(int arr[],  int size) {

    unsigned int randNum;
    srand(time(NULL));
    for (int i = 0; i < size; i++) {
        randNum = rand() % 100 + 1;
        arr[i] = randNum;
    }
}

void addWithCPU(int c[], int a[], int b[], int size) {
    for (int i = 0; i < size; i++) {
        c[i] = a[i] + b[i];
    }
}

int main()
{
    const int arSize = 100;
    int a[arSize] = { 0 };
    int b[arSize] = { 0 };
    randomizeArr(a, arSize);
    randomizeArr(b, arSize);
    int c[arSize] = { 0 };
    int d[arSize] = { 0 };

    // Add vectors in parallel.
    int iterations = 100;
    cudaError cudaStatus;
    auto begin = std::chrono::high_resolution_clock::now();
    for (uint32_t i = 0; i < iterations; ++i)
    {
        cudaStatus = addWithCuda(c, a, b, arSize);
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count();
    std::cout << "Parallel : " << duration / iterations << "ns." << std::endl;

    // Add vectors NOT in parallel.
    auto begin2 = std::chrono::high_resolution_clock::now();
    for (uint32_t i = 0; i < iterations; ++i)
    {
        addWithCPU(d, a, b, arSize);
    }
    auto end2 = std::chrono::high_resolution_clock::now();
    auto duration2 = std::chrono::duration_cast<std::chrono::nanoseconds>(end2 - begin2).count();
    std::cout << "Not Parallel : " << duration2 / iterations << "ns." << std::endl;

    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "addWithCuda failed!");
        fprintf( stderr ,"HERREEEE");
        std::getchar();
        return 1;
    }

    // cudaDeviceReset must be called before exiting in order for profiling and
    // tracing tools such as Nsight and Visual Profiler to show complete traces.
    cudaStatus = cudaDeviceReset();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaDeviceReset failed!");
        return 1;
    }
    std::getchar();

    return 0;
}

// Helper function for using CUDA to add vectors in parallel.
cudaError_t addWithCuda(int *c, const int *a, const int *b, unsigned int size)
{
    int *dev_a = 0;
    int *dev_b = 0;
    int *dev_c = 0;
    cudaError_t cudaStatus;

    // Choose which GPU to run on, change this on a multi-GPU system.
    cudaStatus = cudaSetDevice(0);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaSetDevice failed!  Do you have a CUDA-capable GPU installed?");
        goto Error;
    }

    // Allocate GPU buffers for three vectors (two input, one output)    .
    cudaStatus = cudaMalloc((void**)&dev_c, size * sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&dev_a, size * sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&dev_b, size * sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    // Copy input vectors from host memory to GPU buffers.
    cudaStatus = cudaMemcpy(dev_a, a, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

    cudaStatus = cudaMemcpy(dev_b, b, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

    // Launch a kernel on the GPU with one thread for each element.
    addKernel<<<1, size>>>(dev_c, dev_a, dev_b);

    // Check for any errors launching the kernel
    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "addKernel launch failed: %s\n", cudaGetErrorString(cudaStatus));
        goto Error;
    }

    // cudaDeviceSynchronize waits for the kernel to finish, and returns
    // any errors encountered during the launch.
    cudaStatus = cudaDeviceSynchronize();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus);
        goto Error;
    }

    // Copy output vector from GPU buffer to host memory.
    cudaStatus = cudaMemcpy(c, dev_c, size * sizeof(int), cudaMemcpyDeviceToHost);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

Error:
    cudaFree(dev_c);
    cudaFree(dev_a);
    cudaFree(dev_b);

    return cudaStatus;
}


问:
When Checkbox value is null. Program throws this error" Object cannot be cast from DBNull to other types."
When the checkbox value in database is null it throws error. When it is 0 or 1 it works as expected.

```<code>if (Request.QueryString["Sckey"] != null && Request.QueryString["Sckey"].ToString() != "")
{
    string str_sql1 = "select ScenarioSeq,ScenarioName,FileName,ScenarioNotes,IsUpperCase from Scenario where ScenarioKey=@ScenarioKey;";
    SqlCommand cm = new SqlCommand(str_sql1);
    cm.Parameters.AddWithValue("@ScenarioKey", str_ScKey);
    DataSet ds2 = this.DA.GetDataSet(cm);

    DataRow dr = ds2.Tables[0].Rows[0];
    txt_ScenarioName.Text = dr["ScenarioName"].ToString();
    txt_ScenarioNotes.Text = dr["ScenarioNotes"].ToString();
    ch_Uppercase.Checked = Convert.ToBoolean(dr["IsUpperCase"]);
}
</code>```

答:
```<code>int number;
bool result = Int32.TryParse(dr["IsUpperCase"], out number);
ch_Uppercase.Checked = number;
</code>```

Body:
When the checkbox value in database is null it throws error. When it is 0 or 1 it works as expected.

if (Request.QueryString["Sckey"] != null && Request.QueryString["Sckey"].ToString() != "")
{
    string str_sql1 = "select ScenarioSeq,ScenarioName,FileName,ScenarioNotes,IsUpperCase from Scenario where ScenarioKey=@ScenarioKey;";
    SqlCommand cm = new SqlCommand(str_sql1);
    cm.Parameters.AddWithValue("@ScenarioKey", str_ScKey);
    DataSet ds2 = this.DA.GetDataSet(cm);

    DataRow dr = ds2.Tables[0].Rows[0];
    txt_ScenarioName.Text = dr["ScenarioName"].ToString();
    txt_ScenarioNotes.Text = dr["ScenarioNotes"].ToString();
    ch_Uppercase.Checked = Convert.ToBoolean(dr["IsUpperCase"]);
}


问:
How to change background color of single cell in a windows.forms.datagrid?
I desperately try to figure how to change the background color of a single cell in a winforms dataGridView. I have two columns: if i change content in the second column, i want the cell in the first column of this row to change the background accordingly.

```<code>    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex != 0 || e.RowIndex == -1)
            return;
        if (dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString() == "Red")
            e.CellStyle.BackColor = Color.Red;
        else
            e.CellStyle.BackColor = Color.White;
    }

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex != 1 || e.RowIndex == -1)
            return;
        // dataGridView1.Rows[e.RowIndex].Cells[0]. ???
    }
</code>```

The first event handler sets the backColor of the cells in the first column if they are painted. The second event handler should tell the first cell to paint if the value is changed. If i change the columns width it paints the correct color, so the first handler does the work. But how to trigger the cell painting?

Thanx for help.

答:
Try this.</p>

```<code>dataGridView1.Rows[indexhere].Cells[indexhere].Style.ForeColor = Color.Yellow;
</code>```

Body:
I desperately try to figure how to change the background color of a single cell in a winforms dataGridView. I have two columns: if i change content in the second column, i want the cell in the first column of this row to change the background accordingly.

    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex != 0 || e.RowIndex == -1)
            return;
        if (dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString() == "Red")
            e.CellStyle.BackColor = Color.Red;
        else
            e.CellStyle.BackColor = Color.White;
    }

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex != 1 || e.RowIndex == -1)
            return;
        // dataGridView1.Rows[e.RowIndex].Cells[0]. ???
    }

The first event handler sets the backColor of the cells in the first column if they are painted. The second event handler should tell the first cell to paint if the value is changed. If i change the columns width it paints the correct color, so the first handler does the work. But how to trigger the cell painting?

Thanx for help.

Body:
Try this.

dataGridView1.Rows[indexhere].Cells[indexhere].Style.ForeColor = Color.Yellow;


问:
How to reshape a 3D numpy array?
I have a list of numpy arrays which are actually input images to my CNN. However size of each of my image is not cosistent, and my CNN takes only images which are of dimension 224X224. How do I reshape each of my image into the given dimension?
print(train_images[key].reshape(224, 224,3))

gives me an output

ValueError: total size of new array must be unchanged

I would be very grateful if anybody could help me with this.

答:
New array should have the same amount of values when you are reshaping. What you need is cropping the picture (if it is bigger than 224x224) and padding (if it is smaller than 224x224) or resizing on both occasions.

Cropping is simply slicing with correct indexes:

```<code>def crop(np_img, size):
    v_start = round((np_img.shape[0] - size[0]) / 2)
    h_start = round((np_img.shape[1] - size[1]) / 2)
    return np_img[v_start:v_start+size[1], h_start:h_start+size[0],:]
</code>```

Padding is slightly more complex, this will create a zeros array in desired shape and plug in the values of image inside:

```<code>def pad_image(np_img, size):
    v_start = round((size[0] - np_img.shape[0]) / 2)
    h_start = round((size[1] - np_img.shape[1]) / 2)

    result = np.zeros(size)
    result[v_start:v_start+np_img.shape[1], h_start:h_start+np_img.shape[0], :] = np_img

    return result
</code>```

You can also use np.pad function for it:

```<code>def pad_image(np_img, size):
    v_dif = size[0] - np_img.shape[0]
    h_dif = size[1] - np_img.shape[1]
    return np.lib.pad(np_img, ((v_dif, 0), (h_dif, 0), (0, 0)), 'constant', constant_values=(0))
</code>```

You may realize padding is a bit different in two functions, I didn't want to over complicate the problem and just padded top and left on the second function. Did the both sides in first one since it was easier to calculate.

And finally for resizing, you better use another library. You can use scipy.misc.imresize, its pretty straightforward. This should do it:

```<code>imresize(np_img, size)
</code>```

Title: How to reshape a 3D numpy array?

Body:
New array should have the same amount of values when you are reshaping. What you need is cropping the picture (if it is bigger than 224x224) and padding (if it is smaller than 224x224) or resizing on both occasions.

Cropping is simply slicing with correct indexes:

def crop(np_img, size):
    v_start = round((np_img.shape[0] - size[0]) / 2)
    h_start = round((np_img.shape[1] - size[1]) / 2)
    return np_img[v_start:v_start+size[1], h_start:h_start+size[0],:]

Padding is slightly more complex, this will create a zeros array in desired shape and plug in the values of image inside:

def pad_image(np_img, size):
    v_start = round((size[0] - np_img.shape[0]) / 2)
    h_start = round((size[1] - np_img.shape[1]) / 2)

    result = np.zeros(size)
    result[v_start:v_start+np_img.shape[1], h_start:h_start+np_img.shape[0], :] = np_img

    return result

You can also use np.pad function for it:

def pad_image(np_img, size):
    v_dif = size[0] - np_img.shape[0]
    h_dif = size[1] - np_img.shape[1]
    return np.lib.pad(np_img, ((v_dif, 0), (h_dif, 0), (0, 0)), 'constant', constant_values=(0))

You may realize padding is a bit different in two functions, I didn't want to over complicate the problem and just padded top and left on the second function. Did the both sides in first one since it was easier to calculate.

And finally for resizing, you better use another library. You can use scipy.misc.imresize, its pretty straightforward. This should do it:

imresize(np_img, size)


问:
Angularjs allow one decimal number with after
```<code>   <input type="number"
                           name="content"
                           md-auto-focus

                           ng-model="vm.model.content"
                           ng-required="{{vm.required === null ? true : vm.required}}"
                           ng-attr-ng-max="{{vm.max}}"
                           ng-attr-ng-min="{{vm.min}}">    <div ng-message-exp="['required','min']" ng-if="vm.min != null">
                            <span data-translate
                                  translate-value-length="{{vm.min}}">min</span>
                            </div>
                            <div ng-message="required" ng-if="vm.min == null">
                                <span data-translate>required</span>
                            </div>
                            <div ng-message="number">
                                <span data-translate>numberOnly</span>
                            </div>
                            <div ng-message="max">
                            <span data-translate
                                  translate-value-length="{{vm.max}}">max</span>
                            </div>

                    </div>
</code>```

this is short version of my code.

as you can see here,

https://regex101.com/r/fvPBTW/1
i use same regex.

It accepts 44.44, 44,

but not 44. , 44.444,44.44.44, 44.44.

I think because of number feature.

But i want to be only entered number and one decimal with number after it.

What can i do?

Body:
   <input type="number"
                           name="content"
                           md-auto-focus

                           ng-model="vm.model.content"
                           ng-required="{{vm.required === null ? true : vm.required}}"
                           ng-attr-ng-max="{{vm.max}}"
                           ng-attr-ng-min="{{vm.min}}">

                            min

                                required

                                numberOnly

                            max

this is short version of my code.

as you can see here,

https://regex101.com/r/fvPBTW/1
i use same regex.

It accepts 44.44, 44,

but not 44. , 44.444,44.44.44, 44.44.

I think because of number feature.

But i want to be only entered number and one decimal with number after it.

What can i do?

Body:
Try This :

<input type="number" name="content" md-auto-focus ng-pattern=/^[0-9]+(\.[0-9]{1})?$/>

This will accept only
4 ,
44 ,
4.1 ,
4.2 ,
444.2

But not
4. ,
4.23 ,
4.444 ,
444.23 ,


问:
Can't get form button link to open in new window
I've build a small form button but somehow I can't get the link to open in a new tab. I've tried the target blank attribute but no results. I've also tried changing onclick="window.location.href to onclick="window.open.href but nothing seems to work.. Here is the HTML:

    <form>
<input style="width: 100%;
min-width: 50px;
max-width: 300px;
 padding: 20px;
 cursor: pointer;
 box-shadow: 6px 6px 5px; #999;
 -webkit-box-shadow: 6px 6px 5px #999;
 -moz-box-shadow: 6px 6px 5px #999;
 font-weight: bold;
 background: #9b5103;
 color: #000;
 border-radius: 2px;
 border: 1px solid #999;
 font-size: 150%;" type="button" value="Kayak Tarifa" onclick="window.location.href='https://stackoverflow.com/'" />
</form>

```

答:
Use window.open()

```<code>onclick="window.open('https://stackoverflow.com/')"
</code>```

working demo : https://jsfiddle.net/gaq23jbL/1/

Body:
Use window.open()

onclick="window.open('https://stackoverflow.com/')"

working demo : https://jsfiddle.net/gaq23jbL/1/


问:
replace NULL values with latest non-NULL value in resultset series (SQL Server 2008 R2)
for SQL Server 2008 R2

I have a resultset that looks like this (note [price] is numeric, NULL below represents a
NULL value, the result set is ordered by product_id and timestamp)

```<code>product timestamp          price
------- ----------------   -----
   5678 2008-01-01 12:00   12.34
   5678 2008-01-01 12:01    NULL
   5678 2008-01-01 12:02    NULL
   5678 2008-01-01 12:03   23.45
   5678 2008-01-01 12:04    NULL
</code>```

I want to transform that to a result set that (essentially) copies a non-null value from the latest preceding row, to produce a resultset that looks like this:

```<code>product timestamp          price
------- ----------------   -----
   5678 2008-01-01 12:00   12.34
   5678 2008-01-01 12:01   12.34
   5678 2008-01-01 12:02   12.34
   5678 2008-01-01 12:03   23.45
   5678 2008-01-01 12:04   23.45
</code>```

I don't find any aggregate/windowing function that will allow me to do this (again this ONLY needed for SQL Server 2008 R2.)

I was hoping to find an analytic aggregate function that do this for me, something like...

```<code>LAST_VALUE(price) OVER (PARTITION BY product_id ORDER BY timestamp)
</code>```

But I don't seem to find any way to do a "cumulative latest non-null value" in the window (to bound the window to the preceding rows, rather than the entire partition)

Aside from creating a table-valued user defined function, is there any builtin that would accomplish this?

UPDATE:

Apparently, this functionality is available in the 'Denali' CTP, but not in SQL Server 2008 R2.

LAST_VALUE http://msdn.microsoft.com/en-us/library/hh231517%28v=SQL.110%29.aspx

I just expected it to be available in SQL Server 2008. It's available in Oracle (since 10gR2 at least), and I can do something similar in MySQL 5.1, using a local variable.

http://download.oracle.com/docs/cd/E14072_01/server.112/e10592/functions083.htm

答:
I have a table containing the following data. I want to update all nulls in salary columns with previous value without taking null value.

Table:

```<code>id  name    salary
1   A       4000
2   B
3   C
4   C
5   D       2000
6   E
7   E
8   F       1000
9   G       2000
10  G       3000
11  G       5000
12  G
</code>```

here is the query that works for me.

```<code>select a.*,first_value(a.salary)over(partition by a.value order by a.id) as abc from
(
     select *,sum(case when salary is null then 0 else 1 end)over(order by id) as value from test)a
</code>```

output:

```<code>id  name    salary  Value   abc
1   A       4000    1     4000
2   B               1     4000
3   C               1     4000
4   C               1     4000
5   D       2000    2     2000
6   E               2     2000
7   E               2     2000
8   F       1000    3     1000
9   G       2000    4     2000
10  G       3000    5     3000
11  G       5000    6     5000
12  G               6     5000
</code>```

Body:
for SQL Server 2008 R2

I have a resultset that looks like this (note [price] is numeric, NULL below represents a
NULL value, the result set is ordered by product_id and timestamp)

product timestamp          price
------- ----------------   -----
   5678 2008-01-01 12:00   12.34
   5678 2008-01-01 12:01    NULL
   5678 2008-01-01 12:02    NULL
   5678 2008-01-01 12:03   23.45
   5678 2008-01-01 12:04    NULL

I want to transform that to a result set that (essentially) copies a non-null value from the latest preceding row, to produce a resultset that looks like this:

product timestamp          price
------- ----------------   -----
   5678 2008-01-01 12:00   12.34
   5678 2008-01-01 12:01   12.34
   5678 2008-01-01 12:02   12.34
   5678 2008-01-01 12:03   23.45
   5678 2008-01-01 12:04   23.45

I don't find any aggregate/windowing function that will allow me to do this (again this ONLY needed for SQL Server 2008 R2.)

I was hoping to find an analytic aggregate function that do this for me, something like...

LAST_VALUE(price) OVER (PARTITION BY product_id ORDER BY timestamp)

But I don't seem to find any way to do a "cumulative latest non-null value" in the window (to bound the window to the preceding rows, rather than the entire partition)

Aside from creating a table-valued user defined function, is there any builtin that would accomplish this?

UPDATE:

Apparently, this functionality is available in the 'Denali' CTP, but not in SQL Server 2008 R2.

LAST_VALUE http://msdn.microsoft.com/en-us/library/hh231517%28v=SQL.110%29.aspx

I just expected it to be available in SQL Server 2008. It's available in Oracle (since 10gR2 at least), and I can do something similar in MySQL 5.1, using a local variable.

http://download.oracle.com/docs/cd/E14072_01/server.112/e10592/functions083.htm

Body:
I have a table containing the following data. I want to update all nulls in salary columns with previous value without taking null value.

Table:

id  name    salary
1   A       4000
2   B
3   C
4   C
5   D       2000
6   E
7   E
8   F       1000
9   G       2000
10  G       3000
11  G       5000
12  G

here is the query that works for me.

select a.*,first_value(a.salary)over(partition by a.value order by a.id) as abc from
(
     select *,sum(case when salary is null then 0 else 1 end)over(order by id) as value from test)a

output:

id  name    salary  Value   abc
1   A       4000    1     4000
2   B               1     4000
3   C               1     4000
4   C               1     4000
5   D       2000    2     2000
6   E               2     2000
7   E               2     2000
8   F       1000    3     1000
9   G       2000    4     2000
10  G       3000    5     3000
11  G       5000    6     5000
12  G               6     5000


问:
C++ {} after method what does it means
Hi I have that method

```<code>surface::surface(const surface& s ) :
    ref{s.ref->clone()}
{}
</code>```

What does {} mean after this method? If possible explain me these on some example.

答: This is not an ordinary method: it's a constructor with an empty body. The key here is what happens after the colon (:): these are mem-initializers which tell how to construct the member variables.

Title: C++ {} after method what does it means

Body:
Hi I have that method

surface::surface(const surface& s ) :
    ref{s.ref->clone()}
{}

What does {} mean after this method? If possible explain me these on some example.


问:
Mongodb Monk reauthentication on connection
I have a node program connecting to a MongoDB. Theres a production server where we do proper authentication to connect to the db, but during development on our local machines it's just more tedious to keep track of authentication, especially because most of the time we completely wipe the db often. So resetting up authentication becomes even more tedious. So my solution was to attempt to connect to the db securely, and then if it fails then try to connect to the db in the dev fashion. Heres the code:

```<code>var db = require('monk')('username:password@localhost/TESTR', {authSource:'admin'});

db.catch(function(err) {
    clog.i("MONGO AUTHENTICATION FAILED, USING NO AUTH CLIENT");
    db = require('monk')('localhost/TESTR')
});
</code>```

The problem is that this doesn't work. The rest of the app just complains about the authentication failure the first attempt had. Is there a better solution to this? Or am I just a moron?

答:
```<code>var monk               =  require('monk');//layer used to connect mongodb
 var db                 =  monk('*****:27017/TESTR');
   var collection               =  db.get('collection_name');

    //you can access your collection using the mongo query
          //simple controller action
      module.exports = function(req, res){
        collection.find({}, function(err, cb){
           if(err) {res.json("db exception");}
                 else{res.json(cb)//it returns the db collections}
                   };
       }
</code>```

Body:
I have a node program connecting to a MongoDB. Theres a production server where we do proper authentication to connect to the db, but during development on our local machines it's just more tedious to keep track of authentication, especially because most of the time we completely wipe the db often. So resetting up authentication becomes even more tedious. So my solution was to attempt to connect to the db securely, and then if it fails then try to connect to the db in the dev fashion. Heres the code:

var db = require('monk')('username:password@localhost/TESTR', {authSource:'admin'});

db.catch(function(err) {
    clog.i("MONGO AUTHENTICATION FAILED, USING NO AUTH CLIENT");
    db = require('monk')('localhost/TESTR')
});

The problem is that this doesn't work. The rest of the app just complains about the authentication failure the first attempt had. Is there a better solution to this? Or am I just a moron?


问:
C# enum query linq and general type?
So I want to know that, from my enum value list, how many specific enum value exists.

So I wrote like

```<code>public int GetNumFromList(List<Elements> list, Elements eType)
{
    IEnumerable<Elements> query = //list.Where(p => p.GetType() == eType);
        from listchild in list
        where listchild == eType
        select listchild;
    /*
    Debug.Log("Cur check type is " + eType + " and now selected number is " + query.Count());
    if(query.Count() > 0)
        Debug.Log(" and query 0 value is "+ query.ToArray().GetValue(0) + " type is "+ query.ToArray().GetValue(0).GetType());
        */
    return query.Count();
}
  public enum Elements{Fire, Water, Wood, Metal, Earth, None}
</code>```

So this works well, but can I make this more shorter and neat?

```<code>//list.Where(p => p.GetType() == eType);  This part doesn't worked.
</code>```

And how can make this for generic type, T?

答:
You can do it as short as this:

```<code>public int GetNumFromList(List<Elements> list, Elements eType)
{
  return list.Count(x => x == eType);
}
</code>```

The generic version:

```<code>public int GetNumFromList<T>(List<T> list, T eType)
{
  return list.Count(x => x.Equals(eType));
}
</code>```

Notice your classes should override Equals method in the generic case.

Title: C# enum query linq and general type?

Body:
So I want to know that, from my enum value list, how many specific enum value exists.

So I wrote like

public int GetNumFromList(List<Elements> list, Elements eType)
{
    IEnumerable<Elements> query = //list.Where(p => p.GetType() == eType);
        from listchild in list
        where listchild == eType
        select listchild;
    /*
    Debug.Log("Cur check type is " + eType + " and now selected number is " + query.Count());
    if(query.Count() > 0)
        Debug.Log(" and query 0 value is "+ query.ToArray().GetValue(0) + " type is "+ query.ToArray().GetValue(0).GetType());
        */
    return query.Count();
}
  public enum Elements{Fire, Water, Wood, Metal, Earth, None}

So this works well, but can I make this more shorter and neat?

//list.Where(p => p.GetType() == eType);  This part doesn't worked.

And how can make this for generic type, T?

Body:
You can do it as short as this:

public int GetNumFromList(List<Elements> list, Elements eType)
{
  return list.Count(x => x == eType);
}

The generic version:

public int GetNumFromList<T>(List<T> list, T eType)
{
  return list.Count(x => x.Equals(eType));
}

Notice your classes should override Equals method in the generic case.