问:
How can I get the yesterday's data and show it to my form today?
The idea is that I have this 'Present' form that is a textbox one that the user can input the data.

Now, I want to show yesterday's data(readonly) for comparing the result yesterday vs the result today.

Ex:
Attendance: (yesterday- readonly textbox)

```<code>Andy Shrob
Paula Guinto
Mylene Miles
</code>```

Attendance (TODAY)

```<code>Paula Guinto
Mylene Miles
</code>```

How can I get yesterday and show it so I can see who's present yesterday and who's present today? I'm coding PHP and Javascript

I was thinking of this:

```<code>mysql_query("Select prestoday, presyesterday
FROM attendance
WHERE ???)
</code>```

All ideas are welcome. ;) Whether it be PHP code or Javascript or MYSQL Query

TABLE STRUCTURE:
mysql_select_db("csdcon", $con);

$sql="INSERT INTO attendance (prestoday, presyesterday, userdateinp, yesterdate)
                            VALUES
('$_POST[prestoday]','$_POST[presyesterday]','$_POST[userdateinp]','$_POST[yesterdate]')";

答:
Mysql query

```<code>SELECT DATE_SUB(NOW(), INTERVAL 1 DAY);
</code>```

will return yesterday date...

Hope it helps.

Body:
The idea is that I have this 'Present' form that is a textbox one that the user can input the data.

Now, I want to show yesterday's data(readonly) for comparing the result yesterday vs the result today.

Ex:
Attendance: (yesterday- readonly textbox)

Andy Shrob
Paula Guinto
Mylene Miles

Attendance (TODAY)

Paula Guinto
Mylene Miles

How can I get yesterday and show it so I can see who's present yesterday and who's present today? I'm coding PHP and Javascript

I was thinking of this:

mysql_query("Select prestoday, presyesterday
FROM attendance
WHERE ???)

All ideas are welcome. ;) Whether it be PHP code or Javascript or MYSQL Query

TABLE STRUCTURE:
mysql_select_db("csdcon", $con);

$sql="INSERT INTO attendance (prestoday, presyesterday, userdateinp, yesterdate)
                            VALUES
('$_POST[prestoday]','$_POST[presyesterday]','$_POST[userdateinp]','$_POST[yesterdate]')";

Body:
Mysql query

SELECT DATE_SUB(NOW(), INTERVAL 1 DAY);

will return yesterday date...

Hope it helps.


来源: stackexchange

问:
Using vectorization to reduce for loops, how to use conditional if?
I'm working in a Matlab project and I have a function that is working, but I want to optimize it, reducing the number of for loops that I have in my code.
I read about vectorization, I could use it but how would I include the if conditional statement if I have to test every single value at a time?

```<code>function [y, zf] = MyFunction(x, b, zi)

y = zeros([length(x) 1]);

for n = 1:length(x)
  for k=1:length(zi)
       if n<k
           y(n) = y(n) + b(k)*zi(length(zi)+(n-k)+1);
       else
           y(n) = y(n) + b(k)*x(n-k+1);
       end
   end
end

zf = x(length(x)-length(zi)+1:length(x));
</code>```

I manage to do the vectorization, but I can't figure how to do the conditional, I get the warning:

Variable 'n' might be set by a nonscalar operator

```<code>function [y, zf] = MyFunction(x, b, zi)

y = zeros([length(x) 1]);

n=1:1:length(x); % use of vectorization
for k=1:length(zi)
   if n<k % problem with if
       y = y + b(k)*zi(length(zi)+(n-k)+1);
   else
       y = y + b(k)*x(n-k+1);
   end
end

zf = x(length(x)-length(zi)+1:length(x));
</code>```

答:
Currently n is a vector and k is a scalar, and n<k returns a logical vector. If you directly use if, it would be the same as if all(n), which will only return true when everything in that vector is true! That's unexpected behavior.

I don't know if there's a general way to vectorize codes with if. But in your case, I can do it this way.

% use indice to deal with if
for k=1:length(zi)
   y(1:k-1)=y(1:k-1)+b(k)*zi(length(zi)+2-k:end);
   y(k:end)=y(k:end)+b(k)*x(1:length(x)-k+1);
end
```

<p>I also notice that actually if you <code>cat</code> <code>zi</code> and <code>x</code>, it's no need to use 2 individual statement.</p>

<pre class="lang-matlab prettyprint-override"><code>% assume both zi & x to be column vector
ziandx=[zi;x];
for k=1:length(zi)
   y=y+b(k)*ziandx(length(zi)+2-k:length(zi)+length(x)-k+1);
end
</code>```

Finally, even this for-loop is no need if you use conv. (check the doc for more detail)

ziandx=[zi;x];
s=conv(b(1:length(zi)),ziandx);
y=s(length(zi)+1:length(zi)+length(x))
```

I recommend you to read all three methods and understand the idea, thus you can do it yourself next time.

ContentLicense: CC BY-SA 4.0

Body:
I'm working in a Matlab project and I have a function that is working, but I want to optimize it, reducing the number of for loops that I have in my code.
I read about vectorization, I could use it but how would I include the if conditional statement if I have to test every single value at a time?

function [y, zf] = MyFunction(x, b, zi)

y = zeros([length(x) 1]);

for n = 1:length(x)
  for k=1:length(zi)
       if n<k
           y(n) = y(n) + b(k)*zi(length(zi)+(n-k)+1);
       else
           y(n) = y(n) + b(k)*x(n-k+1);
       end
   end
end

zf = x(length(x)-length(zi)+1:length(x));

I manage to do the vectorization, but I can't figure how to do the conditional, I get the warning:

Variable 'n' might be set by a nonscalar operator

function [y, zf] = MyFunction(x, b, zi)

y = zeros([length(x) 1]);

n=1:1:length(x); % use of vectorization
for k=1:length(zi)
   if n<k % problem with if
       y = y + b(k)*zi(length(zi)+(n-k)+1);
   else
       y = y + b(k)*x(n-k+1);
   end
end

zf = x(length(x)-length(zi)+1:length(x));

Body:
Currently n is a vector and k is a scalar, and n<k returns a logical vector. If you directly use if, it would be the same as if all(n), which will only return true when everything in that vector is true! That's unexpected behavior.

I don't know if there's a general way to vectorize codes with if. But in your case, I can do it this way.

% use indice to deal with if
for k=1:length(zi)
   y(1:k-1)=y(1:k-1)+b(k)*zi(length(zi)+2-k:end);
   y(k:end)=y(k:end)+b(k)*x(1:length(x)-k+1);
end

I also notice that actually if you cat zi and x, it's no need to use 2 individual statement.

% assume both zi & x to be column vector
ziandx=[zi;x];
for k=1:length(zi)
   y=y+b(k)*ziandx(length(zi)+2-k:length(zi)+length(x)-k+1);
end

Finally, even this for-loop is no need if you use conv. (check the doc for more detail)

ziandx=[zi;x];
s=conv(b(1:length(zi)),ziandx);
y=s(length(zi)+1:length(zi)+length(x))

I recommend you to read all three methods and understand the idea, thus you can do it yourself next time.


问:
Django - how to write test for DRF ImageField
I have the following serializer:

```<code>from rest_framework.serializers import Serializer, ImageField

class MySerializer(Serializer):
    avatar = ImageField()
</code>```

how can I write a unit test for it?
I used the Django TestCase, but it raises an error.

```<code>from django.test import TestCase

class MySerializerTest(TestCase):

    def setUp(self):
        self.data = {}
        ...

    def test_image(self):
        import tempfile
        self.data['avatar'] = tempfile.NamedTemporaryFile(suffix=".jpg").file
        r_data = json.dumps(self.data)
        j_data = json.loads(r_data)
        serializer = MySerializer(data=j_data)
        if not serializer.is_valid():
            import pprint
            pprint.pprint(serializer.errors)
        self.assertEqual(serializer.is_valid(), True)
</code>```

but it raises the following error:

TypeError: Object of type 'BufferedRandom' is not JSON serializable

What's my mistake? how can I write a test for image field?

答:
Usually when you upload a file you would use the multipart request format, and the view would convert the image into an InMemoryUploadedFile object, and that gets passed into your serializer

So to fix your tests I'd recommend trying:

```<code>from PIL import Image
from tempfile import NamedTemporaryFile
from django.conf.files.uploadedfile import InMemoryUploadedFile

...

def test_image(self):
    image = Image.new("RGB", (100, 100))
    with NamedTemporaryFile(suffix=".png", mode="w+b") as tmp_file:
        image.save(tmp_file, format="png")
        tmp_file.seek(0)
        byio = BytesIO(temp_file.read())
        inm_file = InMemoryUploadedFile(
            file=byio,
            field_name="avatar",
            name="testImage.png",
            content_type="image/png",
            size=byio.getbuffer().nbytes,
            charset=None,
        )

        self.data['avatar'] = inm_file
        serializer = MySerializer(data=self.data)
        if not serializer.is_valid():
            import pprint
            pprint.pprint(serializer.errors)
        self.assertEqual(serializer.is_valid(), True)
</code>```

What this is doing is:

Create an image in memory using PIL.Image

Create a NamedTemporaryFile to store the Image data

Take the NamedTemporaryFile and read into a InMemoryUploadedFile

Pass this InMemoryUploadedFile into the serializer

Body:
I have the following serializer:

from rest_framework.serializers import Serializer, ImageField

class MySerializer(Serializer):
    avatar = ImageField()

how can I write a unit test for it?
I used the Django TestCase, but it raises an error.

from django.test import TestCase

class MySerializerTest(TestCase):

    def setUp(self):
        self.data = {}
        ...

    def test_image(self):
        import tempfile
        self.data['avatar'] = tempfile.NamedTemporaryFile(suffix=".jpg").file
        r_data = json.dumps(self.data)
        j_data = json.loads(r_data)
        serializer = MySerializer(data=j_data)
        if not serializer.is_valid():
            import pprint
            pprint.pprint(serializer.errors)
        self.assertEqual(serializer.is_valid(), True)

but it raises the following error:

TypeError: Object of type 'BufferedRandom' is not JSON serializable

What's my mistake? how can I write a test for image field?

Body:
Usually when you upload a file you would use the multipart request format, and the view would convert the image into an InMemoryUploadedFile object, and that gets passed into your serializer

So to fix your tests I'd recommend trying:

from PIL import Image
from tempfile import NamedTemporaryFile
from django.conf.files.uploadedfile import InMemoryUploadedFile

...

def test_image(self):
    image = Image.new("RGB", (100, 100))
    with NamedTemporaryFile(suffix=".png", mode="w+b") as tmp_file:
        image.save(tmp_file, format="png")
        tmp_file.seek(0)
        byio = BytesIO(temp_file.read())
        inm_file = InMemoryUploadedFile(
            file=byio,
            field_name="avatar",
            name="testImage.png",
            content_type="image/png",
            size=byio.getbuffer().nbytes,
            charset=None,
        )

        self.data['avatar'] = inm_file
        serializer = MySerializer(data=self.data)
        if not serializer.is_valid():
            import pprint
            pprint.pprint(serializer.errors)
        self.assertEqual(serializer.is_valid(), True)

What this is doing is:

Create an image in memory using PIL.Image

Create a NamedTemporaryFile to store the Image data

Take the NamedTemporaryFile and read into a InMemoryUploadedFile

Pass this InMemoryUploadedFile into the serializer


问:
Workers not being used due to an autoscaler error
This problem relates to the previous question Worker node-status on a Ray EC2 cluster: update-failed; when using Ray for an EC2 cluster. It seems that the cluster is only using the head node despite the config specifying 2 worker nodes. Below is the tailing monitor output, which contains a repeated error that I do not understand. (I am putting this in a new question because there is a lot of text, but it may not be relevant to the problem.)

New error trace:-

```<code>$ ray exec ray_conf.yaml  'tail -n 100 -f /tmp/ray/session_*/logs/monitor*'
2019-05-26 20:33:14,588 INFO updater.py:95 -- NodeUpdater: Waiting for IP of i-04a42aa146ce9b129...
2019-05-26 20:33:14,588 INFO log_timer.py:21 -- NodeUpdater: i-04a42aa146ce9b129: Got IP [LogTimer=414ms]
2019-05-26 20:33:14,594 INFO updater.py:272 -- NodeUpdater: Running tail -n 100 -f /tmp/ray/session_*/logs/monitor* on 100.24.20.34...
==> /tmp/ray/session_2019-05-27_00-31-35_902117_10123/logs/monitor.err <==
2019-05-27 00:31:52,106 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.58.46': 0.33398985862731934}, NodeIdleSeconds=Min=14 Mean=14 Max=14, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=0 Max=0
2019-05-27 00:31:57,062 INFO autoscaler.py:646 -- StandardAutoscaler: 2/2 target nodes (0 pending) (2 updating) (bringup=True)
2019-05-27 00:31:57,063 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.58.46': 0.270449161529541}, NodeIdleSeconds=Min=19 Mean=19 Max=19, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=0 Max=0
2019-05-27 00:31:57,331 INFO updater.py:272 -- NodeUpdater: Running uptime on 172.31.57.23...
2019-05-27 00:32:02,076 INFO updater.py:272 -- NodeUpdater: Running uptime on 172.31.55.204...
2019-05-27 00:32:02,110 INFO autoscaler.py:646 -- StandardAutoscaler: 2/2 target nodes (0 pending) (2 updating) (bringup=True)
2019-05-27 00:32:02,110 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.58.46': 0.2268660068511963}, NodeIdleSeconds=Min=24 Mean=24 Max=24, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=0 Max=0
2019-05-27 00:32:02,544 INFO log_timer.py:21 -- NodeUpdater: i-09402f41cdaf55b70: Got SSH [LogTimer=20562ms]
2019-05-27 00:32:02,547 INFO log_timer.py:21 -- NodeUpdater: i-09402f41cdaf55b70: Initialization commands completed [LogTimer=4ms]
2019-05-27 00:32:02,548 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo pkill -9 apt-get || true on 172.31.55.204...
2019-05-27 00:32:02,641 INFO log_timer.py:21 -- AWSNodeProvider: Set tag ray-node-status=setting-up on ['i-09402f41cdaf55b70'] [LogTimer=97ms]
2019-05-27 00:32:02,661 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo pkill -9 dpkg || true on 172.31.55.204...
2019-05-27 00:32:02,750 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo dpkg --configure -a on 172.31.55.204...
2019-05-27 00:32:02,851 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo apt-get update on 172.31.55.204...
2019-05-27 00:32:07,176 INFO autoscaler.py:646 -- StandardAutoscaler: 2/2 target nodes (0 pending) (2 updating) (bringup=True)
2019-05-27 00:32:07,177 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.58.46': 0.2408006191253662}, NodeIdleSeconds=Min=29 Mean=29 Max=29, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=0 Max=0
2019-05-27 00:32:07,358 INFO updater.py:272 -- NodeUpdater: Running uptime on 172.31.57.23...
2019-05-27 00:32:08,403 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo apt-get install -y build-essential on 172.31.55.204...
2019-05-27 00:32:08,729 INFO log_timer.py:21 -- NodeUpdater: i-09402f41cdaf55b70: Setup commands completed [LogTimer=6181ms]
2019-05-27 00:32:08,729 INFO log_timer.py:21 -- NodeUpdater: i-09402f41cdaf55b70: Applied config c4e33aa96ec128145b1a482dde318746d3aa8234 [LogTimer=26767ms]
2019-05-27 00:32:08,730 ERROR updater.py:145 -- NodeUpdater: i-09402f41cdaf55b70: Error updating (Exit Status 100) ssh -i ~/ray_bootstrap_key.pem -o ConnectTimeout=120s -o StrictHostKeyChecking=no -o ControlMaster=auto -o ControlPath=/tmp/ubuntu_ray_ssh_sockets/18_c48large/%C -o ControlPersist=10s ubuntu@172.31.55.204 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && export  RAY_HEAD_IP=172.31.58.46; sudo apt-get install -y build-essential'
Exception in thread Thread-5:
Traceback (most recent call last):
File "/home/ubuntu/anaconda3/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/updater.py", line 148, in run
raise e
File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/updater.py", line 137, in run
self.do_update()
File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/updater.py", line 236, in do_update
self.ssh_cmd(cmd, redirect=redirect)
File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/updater.py", line 295, in ssh_cmd
stderr=redirect or sys.stderr)
File "/home/ubuntu/anaconda3/lib/python3.6/subprocess.py", line 291, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['ssh', '-i', '~/ray_bootstrap_key.pem', '-o', 'ConnectTimeout=120s', '-o', 'StrictHostKeyChecking=no', '-o', 'ControlMaster=auto', '-o', 'ControlPath=/tmp/ubuntu_ray_ssh_sockets/18_c48large/%C', '-o', 'ControlPersist=10s', 'ubuntu@172.31.55.204', "bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && export    RAY_HEAD_IP=172.31.58.46; sudo apt-get install -y build-essential'"]' returned  non-zero exit status 100.
</code>```

Then the same exception in Thread-7, followed by :-

```<code>==> /tmp/ray/session_2019-05-27_00-31-35_902117_10123/logs/monitor.err <==
2019-05-27 00:33:17,843 INFO autoscaler.py:646 -- StandardAutoscaler: 2/2 target nodes (0 pending) (2 failed to update) (bringup=True)
2019-05-27 00:33:17,844 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.55.204': 65.62029552459717, '172.31.57.23': 45.396358251571655, '172.31.58.46': 0.21964216232299805}, NodeIdleSeconds=Min=100 Mean=100 Max=100, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=37 Max=65
</code>```

... repeated indefinitely.

答: I find that the exit status 100 means "Container released on a lost node".  In which case the problem is an updater failure on the two workers.  This is the same problem as my original: "Worker node-status on a Ray EC2 cluster: update-failed", so I am closing this question.  </p>

Body:
This problem relates to the previous question Worker node-status on a Ray EC2 cluster: update-failed; when using Ray for an EC2 cluster. It seems that the cluster is only using the head node despite the config specifying 2 worker nodes. Below is the tailing monitor output, which contains a repeated error that I do not understand. (I am putting this in a new question because there is a lot of text, but it may not be relevant to the problem.)

New error trace:-

$ ray exec ray_conf.yaml  'tail -n 100 -f /tmp/ray/session_*/logs/monitor*'
2019-05-26 20:33:14,588 INFO updater.py:95 -- NodeUpdater: Waiting for IP of i-04a42aa146ce9b129...
2019-05-26 20:33:14,588 INFO log_timer.py:21 -- NodeUpdater: i-04a42aa146ce9b129: Got IP [LogTimer=414ms]
2019-05-26 20:33:14,594 INFO updater.py:272 -- NodeUpdater: Running tail -n 100 -f /tmp/ray/session_*/logs/monitor* on 100.24.20.34...
==> /tmp/ray/session_2019-05-27_00-31-35_902117_10123/logs/monitor.err <==
2019-05-27 00:31:52,106 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.58.46': 0.33398985862731934}, NodeIdleSeconds=Min=14 Mean=14 Max=14, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=0 Max=0
2019-05-27 00:31:57,062 INFO autoscaler.py:646 -- StandardAutoscaler: 2/2 target nodes (0 pending) (2 updating) (bringup=True)
2019-05-27 00:31:57,063 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.58.46': 0.270449161529541}, NodeIdleSeconds=Min=19 Mean=19 Max=19, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=0 Max=0
2019-05-27 00:31:57,331 INFO updater.py:272 -- NodeUpdater: Running uptime on 172.31.57.23...
2019-05-27 00:32:02,076 INFO updater.py:272 -- NodeUpdater: Running uptime on 172.31.55.204...
2019-05-27 00:32:02,110 INFO autoscaler.py:646 -- StandardAutoscaler: 2/2 target nodes (0 pending) (2 updating) (bringup=True)
2019-05-27 00:32:02,110 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.58.46': 0.2268660068511963}, NodeIdleSeconds=Min=24 Mean=24 Max=24, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=0 Max=0
2019-05-27 00:32:02,544 INFO log_timer.py:21 -- NodeUpdater: i-09402f41cdaf55b70: Got SSH [LogTimer=20562ms]
2019-05-27 00:32:02,547 INFO log_timer.py:21 -- NodeUpdater: i-09402f41cdaf55b70: Initialization commands completed [LogTimer=4ms]
2019-05-27 00:32:02,548 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo pkill -9 apt-get || true on 172.31.55.204...
2019-05-27 00:32:02,641 INFO log_timer.py:21 -- AWSNodeProvider: Set tag ray-node-status=setting-up on ['i-09402f41cdaf55b70'] [LogTimer=97ms]
2019-05-27 00:32:02,661 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo pkill -9 dpkg || true on 172.31.55.204...
2019-05-27 00:32:02,750 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo dpkg --configure -a on 172.31.55.204...
2019-05-27 00:32:02,851 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo apt-get update on 172.31.55.204...
2019-05-27 00:32:07,176 INFO autoscaler.py:646 -- StandardAutoscaler: 2/2 target nodes (0 pending) (2 updating) (bringup=True)
2019-05-27 00:32:07,177 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.58.46': 0.2408006191253662}, NodeIdleSeconds=Min=29 Mean=29 Max=29, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=0 Max=0
2019-05-27 00:32:07,358 INFO updater.py:272 -- NodeUpdater: Running uptime on 172.31.57.23...
2019-05-27 00:32:08,403 INFO updater.py:272 -- NodeUpdater: Running export RAY_HEAD_IP=172.31.58.46; sudo apt-get install -y build-essential on 172.31.55.204...
2019-05-27 00:32:08,729 INFO log_timer.py:21 -- NodeUpdater: i-09402f41cdaf55b70: Setup commands completed [LogTimer=6181ms]
2019-05-27 00:32:08,729 INFO log_timer.py:21 -- NodeUpdater: i-09402f41cdaf55b70: Applied config c4e33aa96ec128145b1a482dde318746d3aa8234 [LogTimer=26767ms]
2019-05-27 00:32:08,730 ERROR updater.py:145 -- NodeUpdater: i-09402f41cdaf55b70: Error updating (Exit Status 100) ssh -i ~/ray_bootstrap_key.pem -o ConnectTimeout=120s -o StrictHostKeyChecking=no -o ControlMaster=auto -o ControlPath=/tmp/ubuntu_ray_ssh_sockets/18_c48large/%C -o ControlPersist=10s ubuntu@172.31.55.204 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && export  RAY_HEAD_IP=172.31.58.46; sudo apt-get install -y build-essential'
Exception in thread Thread-5:
Traceback (most recent call last):
File "/home/ubuntu/anaconda3/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/updater.py", line 148, in run
raise e
File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/updater.py", line 137, in run
self.do_update()
File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/updater.py", line 236, in do_update
self.ssh_cmd(cmd, redirect=redirect)
File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/updater.py", line 295, in ssh_cmd
stderr=redirect or sys.stderr)
File "/home/ubuntu/anaconda3/lib/python3.6/subprocess.py", line 291, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['ssh', '-i', '~/ray_bootstrap_key.pem', '-o', 'ConnectTimeout=120s', '-o', 'StrictHostKeyChecking=no', '-o', 'ControlMaster=auto', '-o', 'ControlPath=/tmp/ubuntu_ray_ssh_sockets/18_c48large/%C', '-o', 'ControlPersist=10s', 'ubuntu@172.31.55.204', "bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && export    RAY_HEAD_IP=172.31.58.46; sudo apt-get install -y build-essential'"]' returned  non-zero exit status 100.

Then the same exception in Thread-7, followed by :-

==> /tmp/ray/session_2019-05-27_00-31-35_902117_10123/logs/monitor.err <==
2019-05-27 00:33:17,843 INFO autoscaler.py:646 -- StandardAutoscaler: 2/2 target nodes (0 pending) (2 failed to update) (bringup=True)
2019-05-27 00:33:17,844 INFO autoscaler.py:647 -- LoadMetrics: MostDelayedHeartbeats={'172.31.55.204': 65.62029552459717, '172.31.57.23': 45.396358251571655, '172.31.58.46': 0.21964216232299805}, NodeIdleSeconds=Min=100 Mean=100 Max=100, NumNodesConnected=1, NumNodesUsed=0.0, ResourceUsage=0.0/36.0 b'CPU', TimeSinceLastHeartbeat=Min=0 Mean=37 Max=65

... repeated indefinitely.


问:
Is self password reset allowed with free Azure AD?I
I have free Azure AD and when I go to the password reset setting in he Azur  portal, it says I need to upgrade to premium to try the feature.

If I try to use the password reset page to change a user password (without upgrading) it tells me there is an error and administrator needs to set password reset policy.

However, I have seen documentations where it says this is possible. Here is a link: https://azure.microsoft.com/en-ca/pricing/details/active-directory/.

I was wondering if I am missing something here, especially after looking at the table in the link above where it says I should be able to reset password with free Azure AD.

答:
With free Azure AD, you have the feature 'Self-Service Password Change for cloud users'.

If you want to use the feature 'Self-Service Password Reset for cloud users'. You need to upgrade to premium.

They are different features.


问:
C# Dll Invoke String Encoding Problem
```<code>    StringBuilder codeline = new StringBuilder(100);

    protected virtual int OnCodeLine(int code, int docId, ref StringBuilder codeline)
            {
////
}
</code>```

This is what i get with *ref StringBuilder*

ĞĞÑĞÒĞÓĞÔĞÕĞÖĞ×ĞØĞÙĞÚĞÛĞÜĞİĞŞĞßĞàĞáĞâĞãĞäĞåĞæĞçĞèĞéĞêĞëĞìĞíĞîĞïĞğĞñĞòĞóĞôĞõĞöĞ÷ĞøĞùĞúĞûĞüĞıĞşĞÿĞÑÑÑÑÑÑÑ Ñ
    ÑÑÑ

ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ

and only with StringBuilder i only get 3

This is what its suppose to return

300 078 9059431

By the way this the MICR Code from Cheques

```<code> [DllImport("mflib.dll")]
    public static extern int mfScanFeeder(int mode, int font, int timeout);

 [UnmanagedFunctionPointer(CallingConvention.StdCall)]
 public delegate int MFS100_CodeLineDelegate(int code, int docId, ref StringBuilder codeline);
 public event MFS100_CodeLineDelegate MFS100_CodeLine;
 private static  MFS100_CodeLineDelegate cache_CodeLine;
</code>```

Update : Here is the Original Code that works in vb6

```<code>    Public Function MFS100_OnCodeline(ByVal code As Long, ByVal docId As Long, ByVal codeline As String) As Long
  Dim i As Integer

  WriteEvent "OnCodeline:"
  WriteEvent "  code = " & code
  WriteEvent "  docId = " & docId
  WriteEvent "  codeline = " & codeline

  MFS100_OnCodeline = -1        ' -1 means: sorting will be done by mfSort()

  g_codeline = codeline

  CScannerForm.TmrSort.enabled = True
End Function
</code>```

Update 2

```<code>  mfSetEvent((int)EventEnum.E_EVENT_CODELINE, cache_CodeLine);

[DllImport("mflib.dll")]
        private static extern int mfSetEvent(int eventID, Delegate callsback);
</code>```

When i use StringBuilder with ref i get a string  that have
32361 length. Without ref i get
only the first value of the
string.

OnCodeLine is for the callback
from the scanner device. What is the
problem ?

答:
You should not pass the StringBuilder by ref. When you do that you say you only get one character back. That's the hallmark of expecting ANSI encoding but actually receiving Unicode (UTF-16). Fix it by specifying the character set:</p>

```<code>[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet=CharSet.Unicode)]
public delegate int MFS100_CodeLineDelegate(int code, int docId, StringBuilder codeline);
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# Dll Invoke String Encoding Problem

Body:
    StringBuilder codeline = new StringBuilder(100);

    protected virtual int OnCodeLine(int code, int docId, ref StringBuilder codeline)
            {
////
}

This is what i get with *ref StringBuilder*

ĞĞÑĞÒĞÓĞÔĞÕĞÖĞ×ĞØĞÙĞÚĞÛĞÜĞİĞŞĞßĞàĞáĞâĞãĞäĞåĞæĞçĞèĞéĞêĞëĞìĞíĞîĞïĞğĞñĞòĞóĞôĞõĞöĞ÷ĞøĞùĞúĞûĞüĞıĞşĞÿĞÑÑÑÑÑÑÑ Ñ
    ÑÑÑ

ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ

and only with StringBuilder i only get 3

This is what its suppose to return

300 078 9059431

By the way this the MICR Code from Cheques

 [DllImport("mflib.dll")]
    public static extern int mfScanFeeder(int mode, int font, int timeout);

 [UnmanagedFunctionPointer(CallingConvention.StdCall)]
 public delegate int MFS100_CodeLineDelegate(int code, int docId, ref StringBuilder codeline);
 public event MFS100_CodeLineDelegate MFS100_CodeLine;
 private static  MFS100_CodeLineDelegate cache_CodeLine;

Update : Here is the Original Code that works in vb6

    Public Function MFS100_OnCodeline(ByVal code As Long, ByVal docId As Long, ByVal codeline As String) As Long
  Dim i As Integer

  WriteEvent "OnCodeline:"
  WriteEvent "  code = " & code
  WriteEvent "  docId = " & docId
  WriteEvent "  codeline = " & codeline

  MFS100_OnCodeline = -1        ' -1 means: sorting will be done by mfSort()

  g_codeline = codeline

  CScannerForm.TmrSort.enabled = True
End Function

Update 2

  mfSetEvent((int)EventEnum.E_EVENT_CODELINE, cache_CodeLine);

[DllImport("mflib.dll")]
        private static extern int mfSetEvent(int eventID, Delegate callsback);

When i use StringBuilder with ref i get a string  that have
32361 length. Without ref i get
only the first value of the
string.

OnCodeLine is for the callback
from the scanner device. What is the
problem ?

Body:
You should not pass the StringBuilder by ref. When you do that you say you only get one character back. That's the hallmark of expecting ANSI encoding but actually receiving Unicode (UTF-16). Fix it by specifying the character set:

[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet=CharSet.Unicode)]
public delegate int MFS100_CodeLineDelegate(int code, int docId, StringBuilder codeline);


问:
Responsive Screens for React Native
How to write stylesheet in react native for apps that scale equally on all devices on both iOS and Android platform?  I tried using react-native-responsive-screen packages but none of the packages did really help to scale the app properly especially when it comes to aligning contents using margins and paddings. Any suggestions on how to overcome this issue?</p>

答:
First, You should understand flexbox and then make your component visible perfectly on all devices.

In this process, Some library can help you.

react-native-lightweight-responsive is so simple.

```<code>import Responsive from 'react-native-lightweight-responsive';

<View style={{
  width: Responsive.width(300),
  height: Reponsive.width(300),
}}/>
</code>```

The codes above will make your components visible identically on all devices.

Title: Responsive Screens for React Native

Body:
First, You should understand flexbox and then make your component visible perfectly on all devices.

In this process, Some library can help you.

react-native-lightweight-responsive is so simple.

import Responsive from 'react-native-lightweight-responsive';

<View style={{
  width: Responsive.width(300),
  height: Reponsive.width(300),
}}/>

The codes above will make your components visible identically on all devices.


问:
How to access params in variadic template function
The old way to make variadic function in C/C++ is using va_list, va_start, va_arg, va_end defined in cstdarg. C++11 comes with variadic function template syntax, but how to access the values?</p>

```<code>//example
#include <iostream>
using namespace std;

template <typename... types>
void print(types... Params){
  //this is not working:
  long Param1 = Params[0];
  long Param2 = Params[1];
}

int main(){
  print(123, 456);
  print(123, "foobar");
}
</code>```

答:
There's a solution using operator<< here: https://stackoverflow.com/a/5495309/5581893

But it's not actually a single function call, it's a series of calls to operator<<, and the function can't be in global scope, it must be a method in a type.

Body:
The old way to make variadic function in C/C++ is using va_list, va_start, va_arg, va_end defined in cstdarg. C++11 comes with variadic function template syntax, but how to access the values?

//example
#include <iostream>
using namespace std;

template <typename... types>
void print(types... Params){
  //this is not working:
  long Param1 = Params[0];
  long Param2 = Params[1];
}

int main(){
  print(123, 456);
  print(123, "foobar");
}


问:
Can someone explain how this loop is printing this tuple?
I'm trying to understand the solutions to question 5 from pythonchallenge, but I don't understand how the for loop is printing that data from the tuple. The solution is from here

Data contains a list of tuples, eg. data = [[(' ', 95)], [(' ', 14), ('#', 5), (' ', 70), ('#', 5), (' ', 1) ...]]

for line in data:
    print("".join([k * v for k, v in line]))
```

What should be printed out is an ASCII graphic made up of '#'.

Body:
I'm trying to understand the solutions to question 5 from pythonchallenge, but I don't understand how the for loop is printing that data from the tuple. The solution is from here

Data contains a list of tuples, eg. data = [[(' ', 95)], [(' ', 14), ('#', 5), (' ', 70), ('#', 5), (' ', 1) ...]]

for line in data:
    print("".join([k * v for k, v in line]))

What should be printed out is an ASCII graphic made up of '#'.

Body:
Consider:

>>> line = [(' ', 3), ('#', 5), (' ', 3), ('#', 5)]
>>> strs = [k * v for k, v in line]

Then:

>>> strs
['   ', '#####', '   ', '#####']

Furthermore:

>>> ''.join(strs)
'   #####   #####'


问:
Efficient algorithm to produce the n-way intersection of sorted arrays in C
I need to produce the intersection between some sorted arrays of integers in C. I know how to find the intersection between two sorted arrays, but I need to do this for more than two arrays, efficiently and without prior knowledge of the number of arrays. I can impose a sensible limit on the maximum number - let's say ten for now. These arrays could be anywhere from a few items to a couple of hundred thousand items long, and are by no means necessarily the same length.

Pseudo-code for producing the intersection of two sorted arrays:

```<code>while i < m and j < n do:
    if array1[i] < array2[j]:
        increment i
    else if array1[i] > array2[j]:
        increment j
    else
        add array1[i] to intersection(array1, array2)
        increment i
        increment j
</code>```

I am working with C, and I am after a clear explanation rather than code.

答: I would first intersect the two smallest arrays, then keep intersecting the result with the smallest intersected array left.  This guarantees that in every single intersect, one of the two arrays in question is no bigger than the smallest original array, which should save some time.</p>

Body:
I need to produce the intersection between some sorted arrays of integers in C. I know how to find the intersection between two sorted arrays, but I need to do this for more than two arrays, efficiently and without prior knowledge of the number of arrays. I can impose a sensible limit on the maximum number - let's say ten for now. These arrays could be anywhere from a few items to a couple of hundred thousand items long, and are by no means necessarily the same length.

Pseudo-code for producing the intersection of two sorted arrays:

while i < m and j < n do:
    if array1[i] < array2[j]:
        increment i
    else if array1[i] > array2[j]:
        increment j
    else
        add array1[i] to intersection(array1, array2)
        increment i
        increment j

I am working with C, and I am after a clear explanation rather than code.

OwnerDisplayName: shelman


问:
Download all files in a path on Jupyter notebook server
As a user in a class that runs Jupyter notebooks for assignments, I have access to the assignments via the web interface. I assume the assignments are stored somewhere in my personal space on the server, and so I should be able to download them. How can I download all files that are in my personal user space? (e.g., wget)

Here's the path structure:

https://urltoserver/user/username

There are several directories: assignments, data, etc.

https://urltoserver/user/username/assignments

https://urltoserver/user/username/data

...

I want to download all the folders (recursively). Just enough that I can launch whatever I see online locally. If there are some forbidden folders, then ok, skip those and download the rest.

Please specify the command exactly as I couldn't figure it out myself (I tried wget)

答:
I am taking Prof. Andrew Ng's Deeplearning.ai program via Coursera. The curriculum uses Jupyter Notebooks online. Along with the notebooks are folders with large files. Here's what I used to successfully download all assignments with the associated files and folders to my local Windows 10 PC.

Start with the following line of code as suggested in the post by Serzan Akhmetov above:

```<code>!tar cvfz allfiles.tar.gz *
</code>```

This produces a tarball which, if small enough, can be downloaded from the Jupyter notebook itself and unzipped using 7-Zip. However, this course has individual files of size 100's of MB and folders with 100's of sample images. The resulting tarball is too large to download via browser.

So add one more line of code to split files into manageable chunk sizes as follows:

```<code>!split -b 50m allfiles.tar.gz allfiles.tar.gz.part.
</code>```

This will split the archive into multiple parts each of size 50 Mb (or your preferred size setting). Each part will have an extension like allfiles.tar.gz.part.xx. Download each part as before.

The final task is to untar the multi-part archive. This is very simple with 7-Zip. Just select the first file in the series for extraction with 7-Zip. This is the file named allfiles.tar.gz.part.aa for the example used. It will pull all the necessary parts together as long as they are in the same folder.

Hope this helps add to Serzan's excellent answer above.

Body:
I am taking Prof. Andrew Ng's Deeplearning.ai program via Coursera. The curriculum uses Jupyter Notebooks online. Along with the notebooks are folders with large files. Here's what I used to successfully download all assignments with the associated files and folders to my local Windows 10 PC.

Start with the following line of code as suggested in the post by Serzan Akhmetov above:

!tar cvfz allfiles.tar.gz *

This produces a tarball which, if small enough, can be downloaded from the Jupyter notebook itself and unzipped using 7-Zip. However, this course has individual files of size 100's of MB and folders with 100's of sample images. The resulting tarball is too large to download via browser.

So add one more line of code to split files into manageable chunk sizes as follows:

!split -b 50m allfiles.tar.gz allfiles.tar.gz.part.

This will split the archive into multiple parts each of size 50 Mb (or your preferred size setting). Each part will have an extension like allfiles.tar.gz.part.xx. Download each part as before.

The final task is to untar the multi-part archive. This is very simple with 7-Zip. Just select the first file in the series for extraction with 7-Zip. This is the file named allfiles.tar.gz.part.aa for the example used. It will pull all the necessary parts together as long as they are in the same folder.

Hope this helps add to Serzan's excellent answer above.


问:
UINavigationController title not aligned with UIBarButton
I have a title for my UINavigationBar, set by calling self.title = "self.title" in my custom UINavigationController and BarButtonItem is installed in the storyboard. Does anyone know what the cause of this misalignment might be and how I would go about fixing it? The title font size is set by calling:

```<code>self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 35),NSAttributedString.Key.foregroundColor: UIColor.white]
</code>```

答:
Check this method of UINavigationBar

```<code>func setTitleVerticalPositionAdjustment(_ adjustment: CGFloat,
                                for barMetrics: UIBarMetrics)
</code>```

Apple Doc

Body:
I have a title for my UINavigationBar, set by calling self.title = "self.title" in my custom UINavigationController and BarButtonItem is installed in the storyboard. Does anyone know what the cause of this misalignment might be and how I would go about fixing it? The title font size is set by calling:

self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 35),NSAttributedString.Key.foregroundColor: UIColor.white]

Body:
Check this method of UINavigationBar

func setTitleVerticalPositionAdjustment(_ adjustment: CGFloat,
                                for barMetrics: UIBarMetrics)

Apple Doc


问:
Where can I find my BuildConfig in the APK analyzer after minifying the code with ProGuard?
Please take a look at the following two images from Analyze APK on Android Studio.

First one is with minifyEnabled = false, and

another one is with minifyEnabled = true (after decoding with mapping.txt of course)

minifyEnabled = false. BuildConfig is there.

minifyEnabled = true (decoded with mapping.txt). BuildConfig is not there.

I can find BuildConfig in classes.dex before minifying, but not after minifying. I can't find any document/discussion about this, but is there some rule to strip BuildConfig from classes.dex after minifying with ProGuard? In that case, does it mean that it is relatively safe to put sensitive information in BuildConfig? Or, probably it is just hidden in some other place?

My ProGuard version is 4.7 if that matters.

答:
If you're using some variables on the BuildConfig, then proguard will not remove it. according to their manual:

The shrinking step detects and removes unused classes, fields, methods, and attributes. The optimization step analyzes and optimizes the bytecode of the methods. The obfuscation step renames the remaining classes, fields, and methods using short meaningless names.

Also, I've been using these options and I've never encountered proguard stripping my information on BuildConfig.

```<code>shrinkResources true
minifyEnabled true
</code>```

Body:
If you're using some variables on the BuildConfig, then proguard will not remove it. according to their manual:

The shrinking step detects and removes unused classes, fields, methods, and attributes. The optimization step analyzes and optimizes the bytecode of the methods. The obfuscation step renames the remaining classes, fields, and methods using short meaningless names.

Also, I've been using these options and I've never encountered proguard stripping my information on BuildConfig.

shrinkResources true
minifyEnabled true


答: Take LinearLayout in your RecyclerView's item  row layout then give android:layout_gravity="center" to LinearLayout.

Title: RecyclerView show many items and make current item in center

Body:
Like this.

Show three items at screen, but left and right item show only edge

When index = 0, show first item at center

When index = n, show current item at center

|-----------------------------------|
|                                   |
|                                   |
|         |---------------|    |----|
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |       1       |    |  2 |
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |---------------|    |----|
|                                   |
|                                   |
|-----------------------------------|

|-----------------------------------|
|                                   |
|                                   |
|----|    |---------------|    |----|
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|  1 |    |       2       |    |  3 |
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|----|    |---------------|    |----|
|                                   |
|                                   |
|-----------------------------------|

I have try SnapHelper, but I don't known how


问:
replaceChild() to move images functioning only once in javascript
I have 3 images side by side, and I have to put 2 buttons under them. Clicking on go forward, the images should move forward and change places, and go backward, vice versa.
I've tried to get this done with arrays, but it is not responding. It moves only once, and does the same action on the one click whether forward or backward. I've pasted my code in the codepen, please have a look. Pasting code here gives me trouble.
https://codepen.io/anon/pen/JqZPVW

```<code>function goleft(){
    imgscroll[0] = document.createElement("imgscl");
    imgscroll[1] = document.createElement("imgscl");
    imgscroll[2] = document.createElement("imgscl");

    for(var index=0 ; index < 3; index++)
    {
        legendChildNodes[index] = document.getElementById("legends").childNodes[index];
        imgscroll[index].src = imgArray[index];
    }
    if(imgArray[0] == document.getElementById("legends").childNodes[0].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[2]);
    }
    else if (imgArray[0] == document.getElementById("legends").childNodes[1].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[2]);
    }
    else if (imgArray[0] == document.getElementById("legends").childNodes[2].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[2]);
    }
}
</code>```

If anyone can help me with this.

答:
Here is some working code. I basically just remove the element and append it to the end, or insert it before the first element dynamically.</p>

```<code>  function goleft() {
         let imageChildNodes = document.getElementById("legends").childNodes;
         let imageList = Array.from(imageChildNodes).filter(function(node) { return node.tagName === 'IMG'; });

         let legendsContainer = document.getElementById("legends");
         legendsContainer.removeChild(imageList[0]);
         legendsContainer.appendChild(imageList[0]);
    }

  function goright() {
         let imageChildNodes = document.getElementById("legends").childNodes;
         let imageList = Array.from(imageChildNodes).filter(function(node) { return node.tagName === 'IMG'; });

         let legendsContainer = document.getElementById("legends");
         legendsContainer.removeChild(imageList[imageList.length - 1]);
         legendsContainer.insertBefore(imageList[imageList.length - 1], imageList[0]);
    }
</code>```

Body:
I have 3 images side by side, and I have to put 2 buttons under them. Clicking on go forward, the images should move forward and change places, and go backward, vice versa.
I've tried to get this done with arrays, but it is not responding. It moves only once, and does the same action on the one click whether forward or backward. I've pasted my code in the codepen, please have a look. Pasting code here gives me trouble.
https://codepen.io/anon/pen/JqZPVW

function goleft(){
    imgscroll[0] = document.createElement("imgscl");
    imgscroll[1] = document.createElement("imgscl");
    imgscroll[2] = document.createElement("imgscl");

    for(var index=0 ; index < 3; index++)
    {
        legendChildNodes[index] = document.getElementById("legends").childNodes[index];
        imgscroll[index].src = imgArray[index];
    }
    if(imgArray[0] == document.getElementById("legends").childNodes[0].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[2]);
    }
    else if (imgArray[0] == document.getElementById("legends").childNodes[1].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[2]);
    }
    else if (imgArray[0] == document.getElementById("legends").childNodes[2].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[2]);
    }
}

If anyone can help me with this.

Body:
Here is some working code. I basically just remove the element and append it to the end, or insert it before the first element dynamically.

  function goleft() {
         let imageChildNodes = document.getElementById("legends").childNodes;
         let imageList = Array.from(imageChildNodes).filter(function(node) { return node.tagName === 'IMG'; });

         let legendsContainer = document.getElementById("legends");
         legendsContainer.removeChild(imageList[0]);
         legendsContainer.appendChild(imageList[0]);
    }

  function goright() {
         let imageChildNodes = document.getElementById("legends").childNodes;
         let imageList = Array.from(imageChildNodes).filter(function(node) { return node.tagName === 'IMG'; });

         let legendsContainer = document.getElementById("legends");
         legendsContainer.removeChild(imageList[imageList.length - 1]);
         legendsContainer.insertBefore(imageList[imageList.length - 1], imageList[0]);
    }


问:
how keep the radio button position at selected one when changes from portrait to landscape
how android radio button code but when changes from portait to landscape selected possition appear</p>

答:
Its probably because you are creating them again in this state in onCrete.

Read this carefully. Then maybe try to save the toogle buttons state in shared preferences or in a bundle.


问:
How to add string ( ' ) in array value on javascript
I have string value of input type=hidden like this:

```<code>A,B,C
</code>```

then i convert that string to array with .split()in javascript:

var menu = $('#title_list').val();
 var arrayMenu = menu.split(",");

and the results:

```<code>arrayMenu = ["A","B","C"]
</code>```

If i want to make that array value to be like this:

```<code>arrayMenu = ["'A'","'B'","'C'"]
</code>```

how to do it?

答:
While string value of input type=hidden is A,B,C Personally I'll try to shape the string then make the array instead of make the array then do a foreach loop again

var menu = $('#title_list').val();
var arrayMenu = ("'"+ menu +"'").replace(/,/g , "','").split(",");
console.log(arrayMenu);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="title_list" value="A,B,C" /></code>```

Explanation for ("'"+InputValue +"'").replace(/,/g , "','").split(",");:

("'"+menu+"'") Add single quote outside the value to be 'A,B,C'

.replace(/,/g , "','") replace the comma with ',' to be 'A' , 'B' , 'C'

.split(",") to split by comma to make the array

Body:
I have string value of input type=hidden like this:

A,B,C

then i convert that string to array with .split()in javascript:

var menu = $('#title_list').val();
 var arrayMenu = menu.split(",");

and the results:

arrayMenu = ["A","B","C"]

If i want to make that array value to be like this:

arrayMenu = ["'A'","'B'","'C'"]

how to do it?

Body:
While string value of input type=hidden is A,B,C Personally I'll try to shape the string then make the array instead of make the array then do a foreach loop again

var menu = $('#title_list').val();
var arrayMenu = ("'"+ menu +"'").replace(/,/g , "','").split(",");
console.log(arrayMenu);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="title_list" value="A,B,C" />

Explanation for ("'"+InputValue +"'").replace(/,/g , "','").split(",");:

("'"+menu+"'") Add single quote outside the value to be 'A,B,C'

.replace(/,/g , "','") replace the comma with ',' to be 'A' , 'B' , 'C'

.split(",") to split by comma to make the array


问:
connecting dialogflow voicebot to twilio number
I am a noob to dialogflow as well as twilio. I am trying to connect my dialogflow bot to a Twilio number.
I got a twilio number and i am using dialogflow small talk set of intents.

What are the steps to connect a dialogflow (voice)bot to a twilio number with voice (not sms, or chat messaging) ?

On twilio side, i found this code
    from flask import Flask
    from twilio.twiml.voice_response import Gather, Redirect, VoiceResponse, Say
    app = Flask(name)

```<code>@app.route("/answer", methods=['GET', 'POST'])
def answer_call():
    """Respond to incoming phone calls with a brief message."""
    # Start our TwiML response
    response = VoiceResponse()

    # Read a message aloud to the caller

    gather = Gather(input='speech',action='some_url')
    gather.say('Welcome to Paradise, please tell us why you\'re calling')
    response.append(gather)

    return str(response)

if __name__ == "__main__":
    app.run(debug=True)
</code>```

1) I understood that i should put the url of my dialogflow bot into the action argument. Am I right?

2) If yes, where do i find this url? Is it related to this ? => https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/v2/projects.agent.sessions/detectIntent

3) Then, what would be the session name?

I am trying to use the box on the right "Try this API": but whatever string i write, the output received is :
"name does not match pattern: /^projects/[^/]+/agent/sessions/[^/]+/contexts/[^/]+$/"

As mentionned i am a newby, so any insights on the above would be greatly appreciated!
Thank you so much in advance!

答:
Twilio developer evangelist here.

I've not worked with Dialogflow and Twilio Voice directly (I prefer to connect voice with Twilio Autopilot as it works out of the box). However I know that there is no direct connect between Twilio Voice and Dialogflow.

You are on the right track though. Using <Gather> will capture the user's speech and translate it to text (actually using Google's Cloud Speech API). That text will be sent to your action URL as the SpeechResult. You can't connect that directly to your Dialogflow API endpoint because Dialogflow will expect the parameter to be different and Twilio will expect the result to be TwiML.

Instead you will want to setup the action endpoint on your own server, retrieve the SpeechResult and then send that on to Dialogflow for the result. You might find it easier to interact with the Dialogflow API by installing the Dialogflow Python client and using it to send the request (check out the documentation here). Once you get the result back from Dialogflow you can then use it to construct TwiML to create a new <Gather> for further input or just a <Say> to return the response.

Let me know if this points you in the right direction.

Body:
I am a noob to dialogflow as well as twilio. I am trying to connect my dialogflow bot to a Twilio number.
I got a twilio number and i am using dialogflow small talk set of intents.

What are the steps to connect a dialogflow (voice)bot to a twilio number with voice (not sms, or chat messaging) ?

On twilio side, i found this code
    from flask import Flask
    from twilio.twiml.voice_response import Gather, Redirect, VoiceResponse, Say
    app = Flask(name)

@app.route("/answer", methods=['GET', 'POST'])
def answer_call():
    """Respond to incoming phone calls with a brief message."""
    # Start our TwiML response
    response = VoiceResponse()

    # Read a message aloud to the caller

    gather = Gather(input='speech',action='some_url')
    gather.say('Welcome to Paradise, please tell us why you\'re calling')
    response.append(gather)

    return str(response)

if __name__ == "__main__":
    app.run(debug=True)

1) I understood that i should put the url of my dialogflow bot into the action argument. Am I right?

2) If yes, where do i find this url? Is it related to this ? => https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/v2/projects.agent.sessions/detectIntent

3) Then, what would be the session name?

I am trying to use the box on the right "Try this API": but whatever string i write, the output received is :
"name does not match pattern: /^projects/[^/]+/agent/sessions/[^/]+/contexts/[^/]+$/"

As mentionned i am a newby, so any insights on the above would be greatly appreciated!
Thank you so much in advance!


问:
How to split a string in Groovy?
I have a groovy script that you can find in this link.

```<code>String str = '# hosts.inventory [vpc] vpc ec2  [ec2] vpc ec2  [project:children] vpc ec2  [author]   [publisher]   [dispatcher] '
str.split((/^\[author\]$/))
for( String values : str )
println(values);
</code>```

I would like to split my string into two parts:

Everything before [author] ie # hosts.inventory [vpc] vpc ec2  [ec2] vpc ec2  [project:children] vpc ec2

Everything after [author] ie [publisher]   [dispatcher]

My regex doesn't seem to work. How do I solve this problem?

答:
This might simply work:

```<code>String str = '# hosts.inventory [vpc] vpc ec2  [ec2] vpc ec2  [project:children] vpc ec2  [author]   [publisher]   [dispatcher] '
values = str.split((/(\[author\])/))
println(values);
</code>```

Groovy

Or I'm guessing that the expression you might be looking for would be similar to:

```<code>(.+)(\[author\])(.+)
</code>```

Where there are three capturing groups, two for before and after [author]:

```<code>(.+)
</code>```

and one for the author:

```<code>(\[author\])
</code>```

Demo

Title: How to split a string in Groovy?

Body:
I have a groovy script that you can find in this link.

String str = '# hosts.inventory [vpc] vpc ec2  [ec2] vpc ec2  [project:children] vpc ec2  [author]   [publisher]   [dispatcher] '
str.split((/^\[author\]$/))
for( String values : str )
println(values);

I would like to split my string into two parts:

Everything before [author] ie # hosts.inventory [vpc] vpc ec2  [ec2] vpc ec2  [project:children] vpc ec2

Everything after [author] ie [publisher]   [dispatcher]

My regex doesn't seem to work. How do I solve this problem?

Body:
This might simply work:

String str = '# hosts.inventory [vpc] vpc ec2  [ec2] vpc ec2  [project:children] vpc ec2  [author]   [publisher]   [dispatcher] '
values = str.split((/(\[author\])/))
println(values);

Groovy

Or I'm guessing that the expression you might be looking for would be similar to:

(.+)(\[author\])(.+)

Where there are three capturing groups, two for before and after [author]:

(.+)

and one for the author:

(\[author\])

Demo


问:
How to store weight values and converting to standard/metric weights?
I'm working on a Vue application, and one of the features deals with weight values. I'm currently storing them in my database as grams, and then converting them to pounds. Eventually I'd like to be able to have the user choose between metric and standard computations. I've created a function that returns four calculations, however they don't seem to add up correctly.

```<code>export const convertToPounds = weight => {
  return (Math.round((weight / 453.592) * 10) / 10).toFixed(2);
};
</code>```

This function is run four times. Once for the total, and three times based on which category the items filter into.

```<code>Total - 4170 grams converts to 9.20 lbs
ValueA - 2700 grams converts to 6.00 lbs
ValueB - 1400 grams converts to 3.10 lbs
ValueC - 70 grams converts to 0.20 lbs
</code>```

Looking at the final conversions though, the three values add up to 9.30 rather than the 9.20 that should be returned.

My question is whether the conversion method is too inaccurate to handle these types of conversions? Or is storing weights in grams not the best way to handle this scenario?

答:
You are rounding. Why are you rounding? Is it so that the UI will not show a long decimal? If so, you should consider rounding at the UI level. Rounding at the data level like that is dangerous, since as you have found out; things will not add up internally and if you use the result of that in another computation then it will drift and become more inaccurate.

Consider a filter to do this, like one this gist (https://gist.github.com/belsrc/672b75d1f89a9a5c192c#file-gistfile1-js-L92):

```<code>Vue.filter('round', function(value, decimals) {
  if(!value) {
    value = 0;
  }

  if(!decimals) {
    decimals = 0;
  }

  value = Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);
  return value;
});
</code>```

Body:
I'm working on a Vue application, and one of the features deals with weight values. I'm currently storing them in my database as grams, and then converting them to pounds. Eventually I'd like to be able to have the user choose between metric and standard computations. I've created a function that returns four calculations, however they don't seem to add up correctly.

export const convertToPounds = weight => {
  return (Math.round((weight / 453.592) * 10) / 10).toFixed(2);
};

This function is run four times. Once for the total, and three times based on which category the items filter into.

Total - 4170 grams converts to 9.20 lbs
ValueA - 2700 grams converts to 6.00 lbs
ValueB - 1400 grams converts to 3.10 lbs
ValueC - 70 grams converts to 0.20 lbs

Looking at the final conversions though, the three values add up to 9.30 rather than the 9.20 that should be returned.

My question is whether the conversion method is too inaccurate to handle these types of conversions? Or is storing weights in grams not the best way to handle this scenario?

Body:
You are rounding. Why are you rounding? Is it so that the UI will not show a long decimal? If so, you should consider rounding at the UI level. Rounding at the data level like that is dangerous, since as you have found out; things will not add up internally and if you use the result of that in another computation then it will drift and become more inaccurate.

Consider a filter to do this, like one this gist (https://gist.github.com/belsrc/672b75d1f89a9a5c192c#file-gistfile1-js-L92):

Vue.filter('round', function(value, decimals) {
  if(!value) {
    value = 0;
  }

  if(!decimals) {
    decimals = 0;
  }

  value = Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);
  return value;
});


问:
Background Image Not Showing On NativeScript Page
I am trying to display a background image on my login page, it is not showing.

I have tried adding the class to the page and my layout. Neither is working.

Is there something in my code that is preventing this for some reason?

```<code><Page loaded="pageLoaded" class="page bgImage" actionBarHidden="true" xmlns="http://www.nativescript.org/tns.xsd">

    <FlexboxLayout class="page">
    <GridLayout rows="auto, auto, auto">
        <StackLayout class="form ">
            <Image class="logo" src="~/images/johnevolve.png" />
            <Label class="header" text="Health Conscious" />

            <StackLayout class="input-field">
                <Label text="Username" />
                <TextField class="input" text="{{ email }}" hint="Email"
                    keyboardType="email" autocorrect="false"
                    autocapitalizationType="none" returnKeyType="next" />
                <Label class="hr-light" />
            </StackLayout>

            <StackLayout class="input-field">
                <Label text="Password" />
                <TextField id="password" class="input" text="{{ password }}"
                    hint="Password" secure="true" returnKeyType="{{ isLoggingIn ? 'done' : 'next' }}" />
                <Label class="hr-light" />
            </StackLayout>

            <StackLayout class="input-field" visibility="{{ !isLoggingIn ? 'visible' : 'collapse' }}">
                <TextField id="confirmPassword" class="input" text="{{ confirmPassword }}"
                    hint="Confirm password" secure="true" returnKeyType="done" />
                <Label class="hr-light" />
            </StackLayout>

            <Button  text="{{ isLoggingIn ? 'Log In' : 'Sign Up' }}" tap="{{ submit }}"
                class="btn btn-primary m-t-20" />

            <Label visibility="{{ isLoggingIn ? 'visible' : 'collapse' }}"
                text="Forgot your password?" class="login-label" tap="{{ forgotPassword }}" />
        </StackLayout>
       </GridLayout>

        <Label class="login-label sign-up-label" tap="{{ toggleForm }}">
            <FormattedString>
                <Span text="{{ isLoggingIn ? 'Don’t have an account? ' : 'Back to Login' }}" />
                <Span text="{{ isLoggingIn ? 'Sign up' : '' }}" class="bold" />
            </FormattedString>
        </Label>
    </FlexboxLayout>

</Page>
</code>```

and my css:

```<code>.bgImage {

background-image: url("~/images/1-login.png");

}
</code>```

Edit: Here is the page css rule in case you need that:

```<code>.page {
  align-items: center;
  flex-direction: column;
}
</code>```

Does anyone know what's going wrong here?

Thank you.

Image In Question:

答:
There was the problem with your FlexboxLayout . It was taking the 100% height and overlapping the background image with it's content.

You can also try with giving background Image to your FlexboxLayout.

```<code><FlexboxLayout class="page bgImage">
</code>```

and in app.css

```<code>.bgImage{
    /* background-color: green; */
    background-image: url("~/images/1-login.png");
    background-repeat: no-repeat;
    background-size: cover
}
</code>```

I have created a playground for you here.

Body:
I am trying to display a background image on my login page, it is not showing.

I have tried adding the class to the page and my layout. Neither is working.

Is there something in my code that is preventing this for some reason?

<Page loaded="pageLoaded" class="page bgImage" actionBarHidden="true" xmlns="http://www.nativescript.org/tns.xsd">

    <FlexboxLayout class="page">
    <GridLayout rows="auto, auto, auto">
        <StackLayout class="form ">
            <Image class="logo" src="~/images/johnevolve.png" />

            <StackLayout class="input-field">

                <TextField class="input" text="{{ email }}" hint="Email"
                    keyboardType="email" autocorrect="false"
                    autocapitalizationType="none" returnKeyType="next" />

            </StackLayout>

            <StackLayout class="input-field">

                <TextField id="password" class="input" text="{{ password }}"
                    hint="Password" secure="true" returnKeyType="{{ isLoggingIn ? 'done' : 'next' }}" />

            </StackLayout>

            <StackLayout class="input-field" visibility="{{ !isLoggingIn ? 'visible' : 'collapse' }}">
                <TextField id="confirmPassword" class="input" text="{{ confirmPassword }}"
                    hint="Confirm password" secure="true" returnKeyType="done" />

            </StackLayout>

            <Button  text="{{ isLoggingIn ? 'Log In' : 'Sign Up' }}" tap="{{ submit }}"
                class="btn btn-primary m-t-20" />

        </StackLayout>
       </GridLayout>

            <FormattedString>

            </FormattedString>

    </FlexboxLayout>

</Page>

and my css:

.bgImage {

background-image: url("~/images/1-login.png");

}

Edit: Here is the page css rule in case you need that:

.page {
  align-items: center;
  flex-direction: column;
}

Does anyone know what's going wrong here?

Thank you.

Image In Question:

Body:
There was the problem with your FlexboxLayout . It was taking the 100% height and overlapping the background image with it's content.

You can also try with giving background Image to your FlexboxLayout.

<FlexboxLayout class="page bgImage">

and in app.css

.bgImage{
    /* background-color: green; */
    background-image: url("~/images/1-login.png");
    background-repeat: no-repeat;
    background-size: cover
}

I have created a playground for you here.


问:
How do I compile a Haskell Mach-O executable that exports a symbol?
How do I compile a Haskell executable (not a library) using GHC >=8.2.1 (preferably on 8.6.*) on macOS 10.14.5 that successfully foreign exports a function (i.e. exposes it as a public symbol in the binary)? This works in GHC 8.0.2 but not in later versions.

I've tried this on ghc 8.0.2 (via stack), 8.2.2 (via both nix and stack), 8.4.4 (via both nix and stack), and 8.6.4 (via both nix and stack). Only 8.0.2 works. I know that 8.2 introduced this change: GHC will now use ld.gold or ld.lld instead of the system’s defaultld, if available. But I am unclear whether 8.0.2 would use a different 'system default' ld in the first place (darwin's ld as opposed to llvm's lld?). I know of ghc's -pgml [ld-program-here] option to set the linker but I haven't been able to manually set it to anything that has successfully compiled and linked anything to test further.

I have this file Main.hs:

module Main where

import Foreign.C

foreign export ccall "my_square" my_square :: CInt -> CInt

my_square :: CInt -> CInt
my_square x = x * x

main :: IO ()
main = putStrLn "FFI Test"
```

<p>With ghc 8.0.2: </p>

```> rm Main.hi Main.o && ghc-8.0.2 Main.hs && nm -g Main | grep my_square
[1 of 1] Compiling Main             ( Main.hs, Main.o )
[some apparently unrelated clang warnings]
Linking Main ...
[further clang warnings]
2544:0000000100001260 T _my_square
```

<p>With ghc 8.6.4, the symbol doesn't seem to be exported, so future attempts to link another program with this symbol fail.</p>

```> rm Main.hi Main.o && ghc-8.6.4 Main.hs && nm -g Main | grep my_square
[1 of 1] Compiling Main             ( Main.hs, Main.o )
Linking Main ...
```

答:
Going off what I said in my comment, neither version of GHC you tested actually exports _my_square from Main. Instead, they export _my_square from Main.o (this is why you can use ghc to compile and link a .c file that uses my_square). When Main.o is linked into the final Main executable, neither GHC tells the linker to export _my_square. GHC 8.6.4 (and, I think, since 8.2) tells the linker to strip unused, unexported symbols, so  _my_square evaporates. GHC 8.0.2 does not, leaving _my_sqaure in the Main executable purely by accident.

You can tell GHC to tell the linker to keep the symbol. The linker option for this is -exported_symbol <symbol>. My GHC actually invokes the linker through gcc, so I have to wrap those two arguments with -Wl. For whatever reason, passing that option to the GHC actually compiling Main.hs causes an error; you have to make Main.o with one bare GHC invocation and then call GHC again to link it into Main, this time with the linker options. Maybe this is peculiar to my system—you may experiment to find a better way.

$ ghc -c Main.hs
# Makes Main.hi Main.o Main_stub.h
$ ghc -optl-Wl,-exported_symbol -optl-Wl,_my_square Main.o -o Main
# Makes Main
$ objdump -t Main | grep _my_square
0000000100000dc0 g     F __TEXT,__text  _my_square
```

I would still recommend filing a GHC issue to make this easier.

Body:
How do I compile a Haskell executable (not a library) using GHC >=8.2.1 (preferably on 8.6.*) on macOS 10.14.5 that successfully foreign exports a function (i.e. exposes it as a public symbol in the binary)? This works in GHC 8.0.2 but not in later versions.

I've tried this on ghc 8.0.2 (via stack), 8.2.2 (via both nix and stack), 8.4.4 (via both nix and stack), and 8.6.4 (via both nix and stack). Only 8.0.2 works. I know that 8.2 introduced this change: GHC will now use ld.gold or ld.lld instead of the system’s defaultld, if available. But I am unclear whether 8.0.2 would use a different 'system default' ld in the first place (darwin's ld as opposed to llvm's lld?). I know of ghc's -pgml [ld-program-here] option to set the linker but I haven't been able to manually set it to anything that has successfully compiled and linked anything to test further.

I have this file Main.hs:

module Main where

import Foreign.C

foreign export ccall "my_square" my_square :: CInt -> CInt

my_square :: CInt -> CInt
my_square x = x * x

main :: IO ()
main = putStrLn "FFI Test"

With ghc 8.0.2:

> rm Main.hi Main.o && ghc-8.0.2 Main.hs && nm -g Main | grep my_square
[1 of 1] Compiling Main             ( Main.hs, Main.o )
[some apparently unrelated clang warnings]
Linking Main ...
[further clang warnings]
2544:0000000100001260 T _my_square

With ghc 8.6.4, the symbol doesn't seem to be exported, so future attempts to link another program with this symbol fail.

> rm Main.hi Main.o && ghc-8.6.4 Main.hs && nm -g Main | grep my_square
[1 of 1] Compiling Main             ( Main.hs, Main.o )
Linking Main ...

Body:
Going off what I said in my comment, neither version of GHC you tested actually exports _my_square from Main. Instead, they export _my_square from Main.o (this is why you can use ghc to compile and link a .c file that uses my_square). When Main.o is linked into the final Main executable, neither GHC tells the linker to export _my_square. GHC 8.6.4 (and, I think, since 8.2) tells the linker to strip unused, unexported symbols, so  _my_square evaporates. GHC 8.0.2 does not, leaving _my_sqaure in the Main executable purely by accident.

You can tell GHC to tell the linker to keep the symbol. The linker option for this is -exported_symbol <symbol>. My GHC actually invokes the linker through gcc, so I have to wrap those two arguments with -Wl. For whatever reason, passing that option to the GHC actually compiling Main.hs causes an error; you have to make Main.o with one bare GHC invocation and then call GHC again to link it into Main, this time with the linker options. Maybe this is peculiar to my system—you may experiment to find a better way.

$ ghc -c Main.hs
# Makes Main.hi Main.o Main_stub.h
$ ghc -optl-Wl,-exported_symbol -optl-Wl,_my_square Main.o -o Main
# Makes Main
$ objdump -t Main | grep _my_square
0000000100000dc0 g     F __TEXT,__text  _my_square

I would still recommend filing a GHC issue to make this easier.


问:
Data manipulation in D3.js
I have the following data:

```<code>var data = [
  {Name:"A", Var:"15", Temp:"20",Lo:"T"},
  {Name:"B", Var:"45", Temp:"40",Lo:"F"},
  {Name:"B", Var:"63", Temp:"340",Lo:"T"},
  {Name:"A", Var:"415", Temp:"450",Lo:"F"},
  {Name:"B", Var:"405", Temp:"940",Lo:"F"},
  {Name:"B", Var:"415", Temp:"410",Lo:"T"},
  {Name:"A", Var:"24", Temp:"51",Lo:"T"},
  {Name:"C", Var:"43", Temp:"40",Lo:"T"},
  {Name:"A", Var:"41", Temp:"40",Lo:"F"}
]
</code>```

I filter the data to get

```<code>dataFiltered = [
  {Name:"A", Var:"15", Temp:"20",Lo:"T"},
  {Name:"A", Var:"415", Temp:"450",Lo:"F"},
  {Name:"A", Var:"24", Temp:"51",Lo:"T"},
  {Name:"A", Var:"41", Temp:"40",Lo:"F"}
]
</code>```

But I want to have a new array of objects like:

```<code>dataNew = [
  {Vt:"35", Tv:"5"},
  {Vt:"865", Tv:"35"},
  {Vt:"75", Tv:"27"},
  {Vt:"80", Tv:"-1"}
]
</code>```

Finally I want to use dataNew to present the aggregated data for Vt (35+865+75+80) and Tv (5+35+27-1) on a pie chart.

Note Vt = Var + Temp and Tv = Temp - Var from dataFiltered.

I really do not know what to do after filtering the data and in particular how to get dataNew.

I leave the code for the filtering part here as well.

```<code>var filteredData = data.filter(function(d) {
    return d.Name == "A";
});
</code>```

答:
You can map that filtered data to desired format using map and than you can use reduce to get total of Tv and Vt values

let dataFiltered = [{Name:"A", Var:"15", Temp:"20",Lo:"T"},{Name:"A", Var:"415", Temp:"450",Lo:"F"},{Name:"A", Var:"24", Temp:"51",Lo:"T"},{Name:"A", Var:"41", Temp:"40",Lo:"F"},]

let newData = dataFiltered.map(({Var, Temp}) => {
  let Vt = Number(Var) + Number(Temp)
  let Tv = Temp - Var
  return {Vt,Tv}
})

console.log(newData)

let aggregateData = newData.reduce((op,{Tv,Vt})=>{
  op['Tv'] = op['Tv'] || 0
  op['Vt'] = op['Vt'] || 0
  op['Tv'] +=Tv
  op['Vt'] +=Vt
  return op
},{})

console.log(aggregateData)```

Title: Data manipulation in D3.js

Body:
I have the following data:

var data = [
  {Name:"A", Var:"15", Temp:"20",Lo:"T"},
  {Name:"B", Var:"45", Temp:"40",Lo:"F"},
  {Name:"B", Var:"63", Temp:"340",Lo:"T"},
  {Name:"A", Var:"415", Temp:"450",Lo:"F"},
  {Name:"B", Var:"405", Temp:"940",Lo:"F"},
  {Name:"B", Var:"415", Temp:"410",Lo:"T"},
  {Name:"A", Var:"24", Temp:"51",Lo:"T"},
  {Name:"C", Var:"43", Temp:"40",Lo:"T"},
  {Name:"A", Var:"41", Temp:"40",Lo:"F"}
]

I filter the data to get

dataFiltered = [
  {Name:"A", Var:"15", Temp:"20",Lo:"T"},
  {Name:"A", Var:"415", Temp:"450",Lo:"F"},
  {Name:"A", Var:"24", Temp:"51",Lo:"T"},
  {Name:"A", Var:"41", Temp:"40",Lo:"F"}
]

But I want to have a new array of objects like:

dataNew = [
  {Vt:"35", Tv:"5"},
  {Vt:"865", Tv:"35"},
  {Vt:"75", Tv:"27"},
  {Vt:"80", Tv:"-1"}
]

Finally I want to use dataNew to present the aggregated data for Vt (35+865+75+80) and Tv (5+35+27-1) on a pie chart.

Note Vt = Var + Temp and Tv = Temp - Var from dataFiltered.

I really do not know what to do after filtering the data and in particular how to get dataNew.

I leave the code for the filtering part here as well.

var filteredData = data.filter(function(d) {
    return d.Name == "A";
});