问:
Java program to convert avro files to text file
Needed help with Java program that takes avro.avsc schema file and avrofile as input and converts them to text file in java.</p>

答:
How can I run below program? I mean what are 3 command line input I can provide?</p>

```<code>import org.apache.avro.*;
import org.apache.avro.generic.*;
import org.apache.avro.file.*;
import org.apache.avro.io.*;

public class AvrotoTextFormatter

{

public static void main ( String args[]) throws Exception

{

    InputStream in = null;
    in = new FileInputStream(args[0]);
    BufferedReader br;
    BufferedInputStream inStream = new BufferedInputStream(in);
    PrintWriter pr1 = new PrintWriter(args[1], "UTF-8");
    PrintWriter pr = new PrintWriter(args[2], "UTF-8");
    StringTokenizer st;
    StringTokenizer st1;
    int row_counter = 0;
    String header_fields = "";
    String content_records = "";
    String sCurrentLine = "";

    GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
    DataFileStream<Object> fileReader = new DataFileStream<Object>(inStream, reader);

    pr1.println(fileReader.getSchema().getFields());

    pr1.close();

    br = new BufferedReader(new java.io.FileReader(args[1]));

    while ((sCurrentLine = br.readLine()) != null)
    {
    st = new StringTokenizer(sCurrentLine," ");
    while (st.hasMoreTokens())
    {
        header_fields = header_fields + st.nextToken() + "|";
        st.nextToken();
        st.nextToken();
    }
    }
    header_fields = header_fields.substring(1,header_fields.length()-1);
    pr.println(header_fields);

    File file = new File(args[0]);
    DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(fileReader.getSchema());
    DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader);
    GenericRecord user = null;
        while (dataFileReader.hasNext())
           {
              content_records = "";
              user = dataFileReader.next(user);
              st1 = new StringTokenizer(header_fields,"|");
              while (st1.hasMoreTokens())
            {
                content_records = content_records + user.get(st1.nextToken()) + "|";
                }
    content_records = content_records.substring(0,content_records.length()-1);
    pr.println(content_records);
            }
    fileReader.close();
    br.close();
    pr.close();

}

}
</code>```

Body:
How can I run below program? I mean what are 3 command line input I can provide?

import org.apache.avro.*;
import org.apache.avro.generic.*;
import org.apache.avro.file.*;
import org.apache.avro.io.*;

public class AvrotoTextFormatter

{

public static void main ( String args[]) throws Exception

{

    InputStream in = null;
    in = new FileInputStream(args[0]);
    BufferedReader br;
    BufferedInputStream inStream = new BufferedInputStream(in);
    PrintWriter pr1 = new PrintWriter(args[1], "UTF-8");
    PrintWriter pr = new PrintWriter(args[2], "UTF-8");
    StringTokenizer st;
    StringTokenizer st1;
    int row_counter = 0;
    String header_fields = "";
    String content_records = "";
    String sCurrentLine = "";

    GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
    DataFileStream<Object> fileReader = new DataFileStream<Object>(inStream, reader);

    pr1.println(fileReader.getSchema().getFields());

    pr1.close();

    br = new BufferedReader(new java.io.FileReader(args[1]));

    while ((sCurrentLine = br.readLine()) != null)
    {
    st = new StringTokenizer(sCurrentLine," ");
    while (st.hasMoreTokens())
    {
        header_fields = header_fields + st.nextToken() + "|";
        st.nextToken();
        st.nextToken();
    }
    }
    header_fields = header_fields.substring(1,header_fields.length()-1);
    pr.println(header_fields);

    File file = new File(args[0]);
    DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(fileReader.getSchema());
    DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader);
    GenericRecord user = null;
        while (dataFileReader.hasNext())
           {
              content_records = "";
              user = dataFileReader.next(user);
              st1 = new StringTokenizer(header_fields,"|");
              while (st1.hasMoreTokens())
            {
                content_records = content_records + user.get(st1.nextToken()) + "|";
                }
    content_records = content_records.substring(0,content_records.length()-1);
    pr.println(content_records);
            }
    fileReader.close();
    br.close();
    pr.close();

}

}


来源: stackexchange

问:
Using divs on an image slider
I have code below for an image slider that stops when you hover on the image. I was wondering if there's anyway to do this but instead of using image tags using just use a div tag so I can create custom shapes to have on the slider with CSS. Can anyone point me in the right direction, when I try replacing the images with divs it stops working. Any thoughts?

#scroller {
  position: absolute;
  left: 33%;
  top: 14%;
}

#scroller .innerScrollArea {
  overflow: hidden;
  position: absolute;
  top: 10%;
  bottom: 0;
  left: 0;
  right: 0;
}

#scroller ul {
  padding: 0;
  top: 10%;
  position: relative;
}

#scroller li {
  padding: 0;
  top: 7%;
  list-style-type: none;
  position: absolute;
}

.test {
width:100px;
height:200px;
background-color:pink;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <!-- SCROLLING IMAGE GALLERY-->

  <div id="scroller" style="width: 536px; height: 263px; margin: 0 auto;">
    <div class="innerScrollArea">
      <ul>
        <li><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/angels_landing_zpsn5dpgsui.jpg" width="536" height="263" /></li>
        <li><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/big_cottonwood_zpszx8qyyik.jpg" width="536" height="263" /></li>
      </ul>
    </div>
  </div>

  <!-- JS SCROLLING IMAGES CODE-->

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  <script type="text/javascript">
    $(function(){
        var scroller = $('#scroller div.innerScrollArea');
        var scrollerContent = scroller.children('ul');
        scrollerContent.children().clone().appendTo(scrollerContent);
        var curX = 0;
        scrollerContent.children().each(function(){
            var $this = $(this);
            $this.css('left', curX);
            curX += $this.outerWidth(true);
        });
        var fullW = curX / 2;
        var viewportW = scroller.width();

        // Scrolling speed management
        var controller = {curSpeed:0, fullSpeed:2};
        var $controller = $(controller);
        var tweenToNewSpeed = function(newSpeed, duration)
        {
            if (duration === undefined)
                duration = 600;
            $controller.stop(true).animate({curSpeed:newSpeed}, duration);
        };

        // Pause on hover
        scroller.hover(function(){
            tweenToNewSpeed(0);
        }, function(){
            tweenToNewSpeed(controller.fullSpeed);
        });

        // Scrolling management; start the automatical scrolling
        var doScroll = function()
        {
            var curX = scroller.scrollLeft();
            var newX = curX + controller.curSpeed;
            if (newX > fullW*2 - viewportW)
                newX -= fullW;
            scroller.scrollLeft(newX);
        };
        setInterval(doScroll, 40);
        tweenToNewSpeed(controller.fullSpeed);
    });
  </script>
</body>

</html></code>```

答:
I added another
 element with a
 and some text in it and it halted just fine. There was no image in it at all.

Check out the fiddle I created.

ContentLicense: CC BY-SA 3.0

Title: Using divs on an image slider

Body:
I added another <li> element with a <div> and some text in it and it halted just fine. There was no image in it at all.

Check out the fiddle I created.


问:
what is PAT (Pre Acceptance Testing)?
What is exactly PAT, When we will do the pre acceptance testing?</p>

答:
Any testing done before acceptance testing.

This would include:

Unit tests

Stress tests

Integration tests

Performance tests

ContentLicense: CC BY-SA 2.5

Title: what is PAT (Pre Acceptance Testing)?


问:
The Process Cannot Access The File...Because it is being used by another process
I'm taking a file and doing 2 things to it. Resizing it and placing it in a picturebox, then resizing it again and saving it.

The first resize operation goes well after dropping it into the window as a thumbnail, however after it has been resized, the second resize operation fails saying its in use.

From my understanding Im not closing the file or stream. A solution to this is the "using" command, but no matter where I put it, I get errors.

First Resize Code:

```<code>    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop);
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }
</code>```

I tried:

```<code>    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        using (string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop));
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }
</code>```

But get a number of errors.

Errors

答:
Without knowing where the second resize operation is I can't be certain, but this should fix your issue.</p>

```<code>private void Form1_DragDrop(object sender, DragEventArgs e)
{
    string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop);
    using (var image = Image.FromFile(droppedfiles[0])){
        PB_Picture.Image = ScaleImage(image, 180, 140);
    }
}
</code>```

Body:
I'm taking a file and doing 2 things to it. Resizing it and placing it in a picturebox, then resizing it again and saving it.

The first resize operation goes well after dropping it into the window as a thumbnail, however after it has been resized, the second resize operation fails saying its in use.

From my understanding Im not closing the file or stream. A solution to this is the "using" command, but no matter where I put it, I get errors.

First Resize Code:

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop);
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }

I tried:

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        using (string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop));
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }

But get a number of errors.

Errors

Body:
Without knowing where the second resize operation is I can't be certain, but this should fix your issue.

private void Form1_DragDrop(object sender, DragEventArgs e)
{
    string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop);
    using (var image = Image.FromFile(droppedfiles[0])){
        PB_Picture.Image = ScaleImage(image, 180, 140);
    }
}


问:
Swift - UISlider doesn't change its value
I programmatically created an UISlider and I created an action that runs evertime I change the slider value. The actions print out the slider.value. The problem is that the value printed out is always 0. Even if I move the slider.
This is the code:</p>

```<code>import UIKit

class EditVC: UIViewController {

var slider : UISlider {
    let frame = CGRect(x: 10, y: 85, width: editView.frame.width - 30, height: 20)
    let slider = UISlider(frame: frame)
    slider.minimumValue = 0
    slider.maximumValue = 10
    slider.isContinuous = true
    slider.addTarget(self, action: #selector(valueChangedFunc), for: .valueChanged)

    return slider

    }

@objc func valueChangedFunc() {
    print(slider.value)
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(slider)
}
}
</code>```

答:
You can use this code, I have tested it and it is working fine

```<code>override func viewDidLoad()
{
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    createMPSlider()
}

func createMPSlider()
{
    let mSlider = UISlider(frame: CGRect(x: 20, y: 200, width: UIScreen.main.bounds.size.width * 0.55, height: 60))
    mSlider.addTarget(self, action: #selector(valueChangedOfSlider(slider:)), for: .valueChanged)
    view .addSubview(mSlider)
}

func valueChangedOfSlider(slider: UISlider)
{
    print(slider.value)
}
</code>```

This above code is working fine. What you need to do is to copy createMPSlider() & valueChangedOfSlider(slider: UISlider) these two complete functions and paste it on your view controller and call createMPSlider() from viewDidLoad it will work.
If you want you can declare  at the top if you want to change customize slider or use it's instance.

Body:
I programmatically created an UISlider and I created an action that runs evertime I change the slider value. The actions print out the slider.value. The problem is that the value printed out is always 0. Even if I move the slider.
This is the code:

import UIKit

class EditVC: UIViewController {

var slider : UISlider {
    let frame = CGRect(x: 10, y: 85, width: editView.frame.width - 30, height: 20)
    let slider = UISlider(frame: frame)
    slider.minimumValue = 0
    slider.maximumValue = 10
    slider.isContinuous = true
    slider.addTarget(self, action: #selector(valueChangedFunc), for: .valueChanged)

    return slider

    }

@objc func valueChangedFunc() {
    print(slider.value)
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(slider)
}
}

Body:
You can use this code, I have tested it and it is working fine

override func viewDidLoad()
{
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    createMPSlider()
}

func createMPSlider()
{
    let mSlider = UISlider(frame: CGRect(x: 20, y: 200, width: UIScreen.main.bounds.size.width * 0.55, height: 60))
    mSlider.addTarget(self, action: #selector(valueChangedOfSlider(slider:)), for: .valueChanged)
    view .addSubview(mSlider)
}

func valueChangedOfSlider(slider: UISlider)
{
    print(slider.value)
}

This above code is working fine. What you need to do is to copy createMPSlider() & valueChangedOfSlider(slider: UISlider) these two complete functions and paste it on your view controller and call createMPSlider() from viewDidLoad it will work.
If you want you can declare  at the top if you want to change customize slider or use it's instance.


问:
Can't Share a Persistent Volume Claim for an EBS Volume between Apps
Is it possible to share a single persistent volume claim (PVC) between two apps (each using a pod)?

I read: Share persistent volume claims amongst containers in Kubernetes/OpenShift but didn't quite get the answer.

I tried to added a PHP app, and MySQL app (with persistent storage) within the same project. Deleted the original persistent volume (PV) and created a new one with read,write,many mode. I set the root password of the MySQL database, and the database works.

Then, I add storage to the PHP app using the same persistent volume claim with a different subpath. I found that I can't turn on both apps. After I turn one on, when I try to turn on the next one, it get stuck at creating container.

MySQL .yaml of the deployment step at openshift:

```<code>  ...
  template:
    metadata:
      creationTimestamp: null
      labels:
        name: mysql
    spec:
      volumes:
        - name: mysql-data
          persistentVolumeClaim:
            claimName: mysql
      containers:
        - name: mysql
        ...
          volumeMounts:
            - name: mysql-data
              mountPath: /var/lib/mysql/data
              subPath: mysql/data
          ...
          terminationMessagePath: /dev/termination-log
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
</code>```

PHP .yaml from deployment step:

```<code> template:
    metadata:
      creationTimestamp: null
      labels:
        app: wiki2
        deploymentconfig: wiki2
    spec:
      volumes:
        - name: volume-959bo  <<----
          persistentVolumeClaim:
            claimName: mysql
      containers:
        - name: wiki2
          ...
          volumeMounts:
            - name: volume-959bo
              mountPath: /opt/app-root/src/w/images
              subPath: wiki/images
          terminationMessagePath: /dev/termination-log
          imagePullPolicy: Always
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      securityContext: {}
</code>```

The volume mount names are different. But that shouldn't make the two pods can't share the PVC. Or, the problem is that they can't both mount the same volume at the same time?? I can't get the termination log at /dev because if it can't mount the volume, the pod doesn't start, and I can't get the log.

The PVC's .yaml (oc get pvc -o yaml)

```<code>apiVersion: v1
items:
- apiVersion: v1
  kind: PersistentVolumeClaim
  metadata:
    annotations:
      pv.kubernetes.io/bind-completed: "yes"
      pv.kubernetes.io/bound-by-controller: "yes"
      volume.beta.kubernetes.io/storage-class: ebs
      volume.beta.kubernetes.io/storage-provisioner: kubernetes.io/aws-ebs
    creationTimestamp: YYYY-MM-DDTHH:MM:SSZ
    name: mysql
    namespace: abcdefghi
    resourceVersion: "123456789"
    selfLink: /api/v1/namespaces/abcdefghi/persistentvolumeclaims/mysql
    uid: ________-____-____-____-____________

  spec:
    accessModes:
    - ReadWriteMany
    resources:
      requests:
        storage: 1Gi
    volumeName: pvc-________-____-____-____-____________
  status:
    accessModes:
    - ReadWriteMany
    capacity:
      storage: 1Gi
    phase: Bound
kind: List
metadata: {}
resourceVersion: ""
selfLink: ""
</code>```

Suspicious Entries from oc get events

```<code>Warning    FailedMount   {controller-manager }
    Failed to attach volume "pvc-________-____-____-____-____________"
    on node "ip-172-__-__-___.xx-xxxx-x.compute.internal"
with:
    Error attaching EBS volume "vol-000a00a00000000a0" to instance
    "i-1111b1b11b1111111": VolumeInUse: vol-000a00a00000000a0 is
    already attached to an instance

Warning   FailedMount   {kubelet ip-172-__-__-___.xx-xxxx-x.compute.internal}
    Unable to mount volumes for pod "the pod for php app":
    timeout expired waiting for volumes to attach/mount for pod "the pod".
    list of unattached/unmounted volumes=
        [volume-959bo default-token-xxxxx]
</code>```

I tried to:

turn on the MySQL app first, and then try to turn on the PHP app

found php app can't start

turn off both apps

turn on the PHP app first, and then try to turn on the MySQL app.

found mysql app can't start

The strange thing is that the event log never says it can't mount volume for the MySQL app.

The remaining volumen to mount is either default-token-xxxxx, or volume-959bo (the volume name in PHP app), but never mysql-data (the volume name in MySQL app).

答:
So the error seems to be caused by the underlying storage you are using, in this case EBS. The OpenShift docs actually specifically state that this is the case for block storage, see here.

I know this will work for both NFS and Glusterfs storage, and have done this in numerous projects using these storage type but unfortunately, in your case it's not supported

Body:
Is it possible to share a single persistent volume claim (PVC) between two apps (each using a pod)?

I read: Share persistent volume claims amongst containers in Kubernetes/OpenShift but didn't quite get the answer.

I tried to added a PHP app, and MySQL app (with persistent storage) within the same project. Deleted the original persistent volume (PV) and created a new one with read,write,many mode. I set the root password of the MySQL database, and the database works.

Then, I add storage to the PHP app using the same persistent volume claim with a different subpath. I found that I can't turn on both apps. After I turn one on, when I try to turn on the next one, it get stuck at creating container.

MySQL .yaml of the deployment step at openshift:

  ...
  template:
    metadata:
      creationTimestamp: null
      labels:
        name: mysql
    spec:
      volumes:
        - name: mysql-data
          persistentVolumeClaim:
            claimName: mysql
      containers:
        - name: mysql
        ...
          volumeMounts:
            - name: mysql-data
              mountPath: /var/lib/mysql/data
              subPath: mysql/data
          ...
          terminationMessagePath: /dev/termination-log
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst

PHP .yaml from deployment step:

 template:
    metadata:
      creationTimestamp: null
      labels:
        app: wiki2
        deploymentconfig: wiki2
    spec:
      volumes:
        - name: volume-959bo  <<----
          persistentVolumeClaim:
            claimName: mysql
      containers:
        - name: wiki2
          ...
          volumeMounts:
            - name: volume-959bo
              mountPath: /opt/app-root/src/w/images
              subPath: wiki/images
          terminationMessagePath: /dev/termination-log
          imagePullPolicy: Always
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      securityContext: {}

The volume mount names are different. But that shouldn't make the two pods can't share the PVC. Or, the problem is that they can't both mount the same volume at the same time?? I can't get the termination log at /dev because if it can't mount the volume, the pod doesn't start, and I can't get the log.

The PVC's .yaml (oc get pvc -o yaml)

apiVersion: v1
items:
- apiVersion: v1
  kind: PersistentVolumeClaim
  metadata:
    annotations:
      pv.kubernetes.io/bind-completed: "yes"
      pv.kubernetes.io/bound-by-controller: "yes"
      volume.beta.kubernetes.io/storage-class: ebs
      volume.beta.kubernetes.io/storage-provisioner: kubernetes.io/aws-ebs
    creationTimestamp: YYYY-MM-DDTHH:MM:SSZ
    name: mysql
    namespace: abcdefghi
    resourceVersion: "123456789"
    selfLink: /api/v1/namespaces/abcdefghi/persistentvolumeclaims/mysql
    uid: ________-____-____-____-____________

  spec:
    accessModes:
    - ReadWriteMany
    resources:
      requests:
        storage: 1Gi
    volumeName: pvc-________-____-____-____-____________
  status:
    accessModes:
    - ReadWriteMany
    capacity:
      storage: 1Gi
    phase: Bound
kind: List
metadata: {}
resourceVersion: ""
selfLink: ""

Suspicious Entries from oc get events

Warning    FailedMount   {controller-manager }
    Failed to attach volume "pvc-________-____-____-____-____________"
    on node "ip-172-__-__-___.xx-xxxx-x.compute.internal"
with:
    Error attaching EBS volume "vol-000a00a00000000a0" to instance
    "i-1111b1b11b1111111": VolumeInUse: vol-000a00a00000000a0 is
    already attached to an instance

Warning   FailedMount   {kubelet ip-172-__-__-___.xx-xxxx-x.compute.internal}
    Unable to mount volumes for pod "the pod for php app":
    timeout expired waiting for volumes to attach/mount for pod "the pod".
    list of unattached/unmounted volumes=
        [volume-959bo default-token-xxxxx]

I tried to:

turn on the MySQL app first, and then try to turn on the PHP app

found php app can't start

turn off both apps

turn on the PHP app first, and then try to turn on the MySQL app.

found mysql app can't start

The strange thing is that the event log never says it can't mount volume for the MySQL app.

The remaining volumen to mount is either default-token-xxxxx, or volume-959bo (the volume name in PHP app), but never mysql-data (the volume name in MySQL app).


问:
C# - OxyPlot how to add plot to windows form
Trying out OxyPlot, installed and referenced packages.  Copying and pasting the example from here http://docs.oxyplot.org/en/latest/getting-started/hello-windows-forms.html but it doesn't recognize plot1 from the last line.  I am guessing because the control isn't added to the form.  How do I add it?  I don't see it in the toolbox, and I tried adding the control to the toolbox and can't find it anywhere.  Thanks.

答:
I just had this very issue myself. I tried adding the Reference (right click References in the Solution Explorer, then browse for the "OxyPlot.dll" and "OxyPlot.WindowsForms.dll" files.) At first it didn't work; kept getting an error.

I noticed there were two versions of the "Oxyplot.dll; a net40 and a net45. I was originally using the net45 version. I copied the net40 version to the same place as the "OxyPlot.WindowsForms.dll", added the Reference, went to the toolbox, added a new tab, then added the reference to the tab (right click tab -> Choose Items, then search for Oxyplot).

I now have Pointer and PlotView in the toolbox. I'm using VS2017 Community with a Forms app. The manual version above worked for me too.


问:
Read until EOF with gzread and inflate float values
So I have this TIFF, with compression 32946, which is COMPRESSION_DEFLATE.

I am reading it by hand and got all the TIFF hex values using hexdump.

I now have a value, data3.txt, which contains all hex values from the hexdump.
Here  it is pasted into docs:

This is my zlib code so far.

```<code>int main(int argc, char **argv) {
    gzFile inFileZ = gzopen("data4.txt", "rb");
    unsigned char unzipBuffer[4];
    gzread(inFileZ, unzipBuffer, 4);
    std::cout<<std::hex<<unzipBuffer<<std::endl;
    z_stream stream;
    stream.next_in = unzipBuffer;
    inflate(&stream, 1);
    float *f = (float *) unzipBuffer;
    printf("%f\n", f);
    gzread(inFileZ, unzipBuffer, 4);
    std::cout<<std::hex<<unzipBuffer<<std::endl;
    stream.next_in = unzipBuffer;
    inflate(&stream, 1);
    f = (float *) unzipBuffer;
    printf("%f\n", f);
    gzclose(inFileZ);
}
</code>```

and I keep getting first the proper hex value, then 0.0000.What am I doing incorrectly?

Also, without copy-pasting code like I did above, how can I continuously read using gzread till the end of the file?

答:
gzopen returns a pointer to a gzfile. inFileZ should be a pointer change the first line to : gzFile *inFileZ = gzopen("data4.txt", "rb");
You can read your whole file whith :

```<code>while(!gzeof(inFileZ){
 //Your code
}
</code>```

Make sure zlib.h is included

Body:
So I have this TIFF, with compression 32946, which is COMPRESSION_DEFLATE.

I am reading it by hand and got all the TIFF hex values using hexdump.

I now have a value, data3.txt, which contains all hex values from the hexdump.
Here  it is pasted into docs:

This is my zlib code so far.

int main(int argc, char **argv) {
    gzFile inFileZ = gzopen("data4.txt", "rb");
    unsigned char unzipBuffer[4];
    gzread(inFileZ, unzipBuffer, 4);
    std::cout<<std::hex<<unzipBuffer<<std::endl;
    z_stream stream;
    stream.next_in = unzipBuffer;
    inflate(&stream, 1);
    float *f = (float *) unzipBuffer;
    printf("%f\n", f);
    gzread(inFileZ, unzipBuffer, 4);
    std::cout<<std::hex<<unzipBuffer<<std::endl;
    stream.next_in = unzipBuffer;
    inflate(&stream, 1);
    f = (float *) unzipBuffer;
    printf("%f\n", f);
    gzclose(inFileZ);
}

and I keep getting first the proper hex value, then 0.0000.What am I doing incorrectly?

Also, without copy-pasting code like I did above, how can I continuously read using gzread till the end of the file?

Body:
gzopen returns a pointer to a gzfile. inFileZ should be a pointer change the first line to : gzFile *inFileZ = gzopen("data4.txt", "rb");
You can read your whole file whith :

while(!gzeof(inFileZ){
 //Your code
}

Make sure zlib.h is included


问:
LEFT JOIN three tables and SUM in LINQ
I have three tables:

products purchased (RecordEntered as A)

products sold in the country (SoldInCountry as B)

products sold outside the country (SoldOutCountry as C)

Each record in A could be:

entered and not yet sold

entered and sold only in the country

entered and sold only out of the country

entered and sold in the country and also outside the country

I started grouping the pieces in table B like so:

```<code>SELECT
A.IdRecord, A.Qty, sum(isnull(B.Qty,0)) AS Expr1
FROM
RecordEntered AS A
LEFT OUTER JOIN
SoldInCountry AS B ON A.IdRecord = B.IdRecord
group by A.IdRecord, A.Qty
</code>```

But I do not know how to go on.

I would like a query to show me how many pieces I still have in stock.
Like this:

```<code>A.Qty - (SUM(ISNULL(B.Qty, 0)) + SUM(ISNULL(C.Qty, 0)))
</code>```

I wrote an example in SQL, but the goal is LINQ:

```<code>from a in _ctx.....
  where .....
  select...
</code>```

thanks

答:
It isn't easy to do a full outer join in LINQ (see my answer here: https://stackoverflow.com/a/43669055/2557128) but you don't need that to solve this:

```<code>var numInStock = from item in RecordEntered
             select new {
                 item.Code,
                 Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).SingleOrDefault() -
             (from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).SingleOrDefault()
             };
</code>```

I assumed there would only be one sold record of each type for an item, if there could be more than one, you would need to Sum the matching records:

```<code>var numInStock = from item in RecordEntered
             select new {
                 item.Code,
                 Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).DefaultIfEmpty().Sum() -
             (from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).DefaultIfEmpty().Sum()
             };
</code>```

Title: LEFT JOIN three tables and SUM in LINQ

Body:
I have three tables:

products purchased (RecordEntered as A)

products sold in the country (SoldInCountry as B)

products sold outside the country (SoldOutCountry as C)

Each record in A could be:

entered and not yet sold

entered and sold only in the country

entered and sold only out of the country

entered and sold in the country and also outside the country

I started grouping the pieces in table B like so:

SELECT
A.IdRecord, A.Qty, sum(isnull(B.Qty,0)) AS Expr1
FROM
RecordEntered AS A
LEFT OUTER JOIN
SoldInCountry AS B ON A.IdRecord = B.IdRecord
group by A.IdRecord, A.Qty

But I do not know how to go on.

I would like a query to show me how many pieces I still have in stock.
Like this:

A.Qty - (SUM(ISNULL(B.Qty, 0)) + SUM(ISNULL(C.Qty, 0)))

I wrote an example in SQL, but the goal is LINQ:

from a in _ctx.....
  where .....
  select...

thanks

Body:
It isn't easy to do a full outer join in LINQ (see my answer here: https://stackoverflow.com/a/43669055/2557128) but you don't need that to solve this:

var numInStock = from item in RecordEntered
             select new {
                 item.Code,
                 Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).SingleOrDefault() -
             (from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).SingleOrDefault()
             };

I assumed there would only be one sold record of each type for an item, if there could be more than one, you would need to Sum the matching records:

var numInStock = from item in RecordEntered
             select new {
                 item.Code,
                 Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).DefaultIfEmpty().Sum() -
             (from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).DefaultIfEmpty().Sum()
             };


问:
If there is no distinct between read, compile and runtime in Lisp, can someone give me some intuitive examples?
As I read blog Revenge of the nerds, It says (in what made Lisp different section):

The whole language there all the time. There is no real distinction between read-time, compile-time, and runtime. You can compile or run code while reading, read or run code while compiling, and read or compile code at runtime.

Running code at read-time lets users reprogram Lisp's syntax; running code at compile-time is the basis of macros; compiling at runtime is the basis of Lisp's use as an extension language in programs like Emacs; and reading at runtime enables programs to communicate using s-expressions, an idea recently reinvented as XML.

In order to understand this sentence, I draw a statechart diagram:

I have two questions:

how to understand to read at runtime enable programming to communicate using s-expression, an idea reinvented as XML

what can we do when compiling at read time or reading at compile time？

答:
Common Lisp

READ is a function which reads s-expressions and returns Lisp data.

```<code>CL-USER> (read)
(defun example (n) (if (zerop n) 1 (* (example (1- n)) n)))  ; <- input
(DEFUN EXAMPLE (N) (IF (ZEROP N) 1 (* (EXAMPLE (1- N)) N)))  ; <- output
</code>```

The last result again:

```<code>CL-USER> *
(DEFUN EXAMPLE (N) (IF (ZEROP N) 1 (* (EXAMPLE (1- N)) N)))
</code>```

Setting the variable code to the last result.

```<code>CL-USER> (setf code *)
(DEFUN EXAMPLE (N) (IF (ZEROP N) 1 (* (EXAMPLE (1- N)) N)))
</code>```

What is the third element?

```<code>CL-USER> (third code)
(N)
</code>```

We can evaluate this list, since it looks like valid Lisp code:

```<code>CL-USER> (eval code)
EXAMPLE
</code>```

The function EXAMPLE has been defined. Let's get the function object:

```<code>CL-USER> (function example)
#<interpreted function EXAMPLE 21ADA5B2>
</code>```

It's an interpreted function. We use a Lisp interpreter.

Let's use the function by mapping it over a list:

```<code>CL-USER> (mapcar (function example) '(1 2 3 4 5))
(1 2 6 24 120)
</code>```

Let's compile the function:

```<code>CL-USER> (compile 'example)
EXAMPLE
NIL
NIL
</code>```

The function has been compiled successfully. The compiler has no warnings and the function should now run much faster.

Let's use it again:

```<code>CL-USER> (mapcar (function example) '(1 2 3 4 5))
(1 2 6 24 120)
</code>```

This is the same result, but probably much faster computed.

Since it is now compiled, let's disassemble the function:

```<code>CL-USER> (disassemble #'example)
0          : #xE3E06A03 : mvn            tmp1, #12288
4          : #xE18D6626 : orr            tmp1, sp, tmp1, lsr #12
8          : #xE5166030 : ldr            tmp1, [tmp1, #-48]
</code>```

... and a lot more lines of ARM assembler machine code

Body:
Common Lisp

READ is a function which reads s-expressions and returns Lisp data.

CL-USER> (read)
(defun example (n) (if (zerop n) 1 (* (example (1- n)) n)))  ; <- input
(DEFUN EXAMPLE (N) (IF (ZEROP N) 1 (* (EXAMPLE (1- N)) N)))  ; <- output

The last result again:

CL-USER> *
(DEFUN EXAMPLE (N) (IF (ZEROP N) 1 (* (EXAMPLE (1- N)) N)))

Setting the variable code to the last result.

CL-USER> (setf code *)
(DEFUN EXAMPLE (N) (IF (ZEROP N) 1 (* (EXAMPLE (1- N)) N)))

What is the third element?

CL-USER> (third code)
(N)

We can evaluate this list, since it looks like valid Lisp code:

CL-USER> (eval code)
EXAMPLE

The function EXAMPLE has been defined. Let's get the function object:

CL-USER> (function example)
#<interpreted function EXAMPLE 21ADA5B2>

It's an interpreted function. We use a Lisp interpreter.

Let's use the function by mapping it over a list:

CL-USER> (mapcar (function example) '(1 2 3 4 5))
(1 2 6 24 120)

Let's compile the function:

CL-USER> (compile 'example)
EXAMPLE
NIL
NIL

The function has been compiled successfully. The compiler has no warnings and the function should now run much faster.

Let's use it again:

CL-USER> (mapcar (function example) '(1 2 3 4 5))
(1 2 6 24 120)

This is the same result, but probably much faster computed.

Since it is now compiled, let's disassemble the function:

CL-USER> (disassemble #'example)
0          : #xE3E06A03 : mvn            tmp1, #12288
4          : #xE18D6626 : orr            tmp1, sp, tmp1, lsr #12
8          : #xE5166030 : ldr            tmp1, [tmp1, #-48]

... and a lot more lines of ARM assembler machine code


问:
Spring OAuth2 asking for password when sending refresh token
I have been trying to use OAuth2 for the first time with Spring Boot.

The infrastructure is working, however, when the authorization token is expired and I send the refresh token to get a new one, I am also being asked for username and password.

The question: shouldn't the refresh token be enough to get a new authorization token? Otherwise I would need to store the user credentials, which does not sound right.

Is this something I am totally getting wrong?

Thanks!

My ResourceServer config:

```<code>@Configuration
@EnableResourceServer
public class OAuth2ConfigResource extends
ResourceServerConfigurerAdapter {

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http
            .requestMatchers()
              .antMatchers("/**")
            .and()
            .authorizeRequests()
              .antMatchers("/api/secure/**")
                .access("#oauth2.clientHasRole('ADMIN')")
              .antMatchers("/api/public/**")
                .access("#oauth2.clientHasRole('USER')");
  }

  @Override
  public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources.tokenStore(tokenStore());
  }

  @Bean
  public TokenStore tokenStore() {
    return new JwtTokenStore(jwtAccessTokenConverter());
  }

  @Bean
  public JwtAccessTokenConverter jwtAccessTokenConverter() {
    JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
    return tokenConverter;
  }
}
</code>```

My AuthServer config:

```<code>@Configuration
</code>```

@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

```<code>@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;

@Autowired
private AuthenticationManager authenticationManager;

private int expiration = 60;

@Bean
@Autowired
public PasswordEncoder passwordEncoder(@Value("${jwt.secret}") String secret) {
    return new StandardPasswordEncoder(secret);
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer.allowFormAuthenticationForClients();
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
    configurer.authenticationManager(authenticationManager);
    configurer.userDetailsService(userDetailsService);
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

    clients.inMemory()
    .withClient("user1")
    .secret("pass1")
    .accessTokenValiditySeconds(expiration)
    .authorities("ADMIN", "USER")
    .scopes("read")
    .authorizedGrantTypes("password", "refresh_token", "client_credentials")
    .and()
    .withClient("user2")
    .secret("pass2")
    .accessTokenValiditySeconds(expiration)
    .authorities("USER")
    .scopes("read")
    .authorizedGrantTypes("password", "refresh_token", "client_credentials");
}
</code>```

}

The usage:

1. Aquiring the token

```<code>curl -X POST --user 'user2:pass2' -d 'grant_type=password&username=user2&password=pass2' http://localhost:8080/oauth/token
</code>```

2. Reaching the API

```<code>curl -i -H "Accept: application/json" -H "Authorization: Bearer 260480f7-3e94-4811-a49d-b385dff83f4a" http://localhost:8080/api/public/request/felipe
</code>```

3. Using the refresh token to get a new auth token

```<code>curl -X POST --user 'user2:pass2' -d 'grant_type=refresh_token&refresh_token=48c9f1db-9252-47a0-9a28-091caa775e4c' http://localhost:8080/oauth/token
</code>```

As mentioned, this infrastructure works perfectly, however, I do not understand why I should pass the credentials (assuming there's no workarounds) when using refresh tokens, since this token is there just to prevent - to the best of my understanding - the exposition of credentials.

答:
1. User Credentials

username and password are parameters to specify user credentials (user ID and password).

```<code>grant_type=password&username={User-ID}&password={Password}
</code>```

2. Client Credentials

Authorization header included in requests to the token endpoint contains client credentials (client ID and client secret).

```<code>--user '{Client-ID}:{Client-Secret}'
</code>```

3. Recommendation

You should change the following code:

```<code>.withClient("user2")
.secret("pass2")
</code>```

to

```<code>.withClient("clientId2")
.secret("clientSecret2")
</code>```

to avoid confusion.

Body:
I have been trying to use OAuth2 for the first time with Spring Boot.

The infrastructure is working, however, when the authorization token is expired and I send the refresh token to get a new one, I am also being asked for username and password.

The question: shouldn't the refresh token be enough to get a new authorization token? Otherwise I would need to store the user credentials, which does not sound right.

Is this something I am totally getting wrong?

Thanks!

My ResourceServer config:

@Configuration
@EnableResourceServer
public class OAuth2ConfigResource extends
ResourceServerConfigurerAdapter {

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http
            .requestMatchers()
              .antMatchers("/**")
            .and()
            .authorizeRequests()
              .antMatchers("/api/secure/**")
                .access("#oauth2.clientHasRole('ADMIN')")
              .antMatchers("/api/public/**")
                .access("#oauth2.clientHasRole('USER')");
  }

  @Override
  public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources.tokenStore(tokenStore());
  }

  @Bean
  public TokenStore tokenStore() {
    return new JwtTokenStore(jwtAccessTokenConverter());
  }

  @Bean
  public JwtAccessTokenConverter jwtAccessTokenConverter() {
    JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
    return tokenConverter;
  }
}

My AuthServer config:

@Configuration

@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;

@Autowired
private AuthenticationManager authenticationManager;

private int expiration = 60;

@Bean
@Autowired
public PasswordEncoder passwordEncoder(@Value("${jwt.secret}") String secret) {
    return new StandardPasswordEncoder(secret);
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer.allowFormAuthenticationForClients();
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
    configurer.authenticationManager(authenticationManager);
    configurer.userDetailsService(userDetailsService);
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

    clients.inMemory()
    .withClient("user1")
    .secret("pass1")
    .accessTokenValiditySeconds(expiration)
    .authorities("ADMIN", "USER")
    .scopes("read")
    .authorizedGrantTypes("password", "refresh_token", "client_credentials")
    .and()
    .withClient("user2")
    .secret("pass2")
    .accessTokenValiditySeconds(expiration)
    .authorities("USER")
    .scopes("read")
    .authorizedGrantTypes("password", "refresh_token", "client_credentials");
}

}

The usage:

1. Aquiring the token

curl -X POST --user 'user2:pass2' -d 'grant_type=password&username=user2&password=pass2' http://localhost:8080/oauth/token

2. Reaching the API

curl -i -H "Accept: application/json" -H "Authorization: Bearer 260480f7-3e94-4811-a49d-b385dff83f4a" http://localhost:8080/api/public/request/felipe

3. Using the refresh token to get a new auth token

curl -X POST --user 'user2:pass2' -d 'grant_type=refresh_token&refresh_token=48c9f1db-9252-47a0-9a28-091caa775e4c' http://localhost:8080/oauth/token

As mentioned, this infrastructure works perfectly, however, I do not understand why I should pass the credentials (assuming there's no workarounds) when using refresh tokens, since this token is there just to prevent - to the best of my understanding - the exposition of credentials.

Body:
1. User Credentials

username and password are parameters to specify user credentials (user ID and password).

grant_type=password&username={User-ID}&password={Password}

2. Client Credentials

Authorization header included in requests to the token endpoint contains client credentials (client ID and client secret).

--user '{Client-ID}:{Client-Secret}'

3. Recommendation

You should change the following code:

.withClient("user2")
.secret("pass2")

to

.withClient("clientId2")
.secret("clientSecret2")

to avoid confusion.


问:
Any way to start Google Chrome in headless mode?
I carefully revised the list of switches at http://peter.sh/experiments/chromium-command-line-switches/#chrome-frame and I couldn't find anything that would launch Chrome in a hidden background process.

The closest I was able to is --keep-alive-for-test + custom packaged app, but the app fails to execute any passed code because (the way it reports) "no window - ChromeHidden".

答:
Chrome 59 has the ability to create instance as headless.
Find the below tutorial
https://www.automation99.com/2017/07/how-to-use-chrome-headless-using.html?m=1</p>


问:
Using Node.js to Send Database Queries to Website
I'm new to Node.js and am unsure how to use it for my website as defined in the following example. Here's what I'd like to do:

I have a website http://example.com with a real-time stock dashboard located at http://example.com/stocks. I'd like to use Node to

1) populate a mysql database (located on my web server through Namecheap hosting) with stock data scraped every 5 minutes (say from Bloomberg)

2) pull the stock data from the mysql database and serve it to the page to be displayed through the dashboard on a client's end when they visit http://example.com/stocks.

I'm by no means asking for the code behind this, I just don't know where to start! Every tutorial online seems to use their machine localhost as the only place to display and use their Node output. How can I use Node to achieve the tasks above through my web server associated with my domain and not my localhost machine? Thanks for any advice!

答:
All examples are using localhost, because they are being developed locally. In order to have your application on http://example.com, you will need to deploy your application to a host machine.

In order to develop something like this in NodeJS, there are few things you should consider using. I would suggest following steps

Implementation of scheduled job, job that will collect/scrap the data from the site (see node-schedule module for details)

Store collected data in database of choice (you have mentioned mysql)

Implement socket connection (for example socket.io) which will be used by a web app to connect to server and receive the data in real time

Implementation of UI with websocket connection to the server

Take deployment as a last step (step where you see your application running on http://example.com). You need to find appropriate host, install all relevant stuff used in development (nodejs, mysql, npm modules,...), and then you can start your application on new host.

Hope this helps a bit on where to start and how to develop/deploy this in NodeJS.


问:
UISlider throwing NSRangeException
Despite setting each slider's minimum, maximum, and current values to their defaults in the storyboard, moving the slider throws an error saying that the value was somehow moved to 2. In addition, this error only started when I added:

```<code>var lElbowX = Int()
var rElbowX = Int()
var lElbowY = Int()
var rElbowY = Int()
var lWristX = Int()
var lWristY = Int()
var rWristX = Int()
var rWristY = Int()
var lKneeX = Int()
var lKneeY = Int()
var rKneeX = Int()
var rKneeY = Int()
var lAnkleX = Int()
var lAnkleY = Int()
var rAnkleX = Int()
var rAnkleY = Int()
</code>```

and

```<code>@IBAction func vertical(_ sender: Any) {//The action function used to be empty
    if jointPicker.selectedRow(inComponent: 2) == 1 {//left
        if jointPicker.selectedRow(inComponent: 1) == 1 {//lNeck
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 2 {//lShoulder
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 3 {//lElbow
            lElbowY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 4 {//lWrist
            lWristY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 5 {//lSpine
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 6 {//lHip
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 7 {//lKnee
            lKneeY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 8 {//lAnkle
            lAnkleY = Int((verticalSlider.value - 0.5) * 200)
        }

    }
    if jointPicker.selectedRow(inComponent: 2) == 2 {//right
        if jointPicker.selectedRow(inComponent: 1) == 1 {//rNeck
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 2 {//rShoulder
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 3 {//rElbow
            rElbowY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 4 {//rWrist
            rWristY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 5 {//rSpine
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 6 {//rHip
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 7 {//rKnee
            rKneeY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 8 {//rAnkle
            rAnkleY = Int((verticalSlider.value - 0.5) * 200)
        }

    }
}
@IBAction func horizontal(_ sender: Any) {//The action function used to be empty
    if jointPicker.selectedRow(inComponent: 2) == 1 {//left
        if jointPicker.selectedRow(inComponent: 1) == 1 {//lNeck
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 2 {//lShoulder
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 3 {//lElbow
            lElbowX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 4 {//lWrist
            lWristX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 5 {//lSpine
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 6 {//lHip
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 7 {//lKnee
            lKneeX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 8 {//lAnkle
            lAnkleX = Int((horizontalSlider.value - 0.5) * 200)
        }

    }
    if jointPicker.selectedRow(inComponent: 2) == 2 {//right
        if jointPicker.selectedRow(inComponent: 1) == 1 {//rNeck
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 2 {//rShoulder
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 3 {//rElbow
            rElbowX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 4 {//rWrist
            rWristX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 5 {//rSpine
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 6 {//rHip
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 7 {//rKnee
            rKneeX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 8 {//rAnkle
            rAnkleX = Int((horizontalSlider.value - 0.5) * 200)
        }

    }
}
</code>```

Call Stack:

```<code>2017-07-03 12:38:06.856 Exercise Generator[50942:2970421] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'
*** First throw call stack:
(
0   CoreFoundation                      0x0000000110352d4b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x000000010d66521e objc_exception_throw + 48
2   CoreFoundation                      0x00000001102842eb -[__NSArrayM objectAtIndex:] + 203
3   UIKit                               0x000000010db187ba -[UIPickerView selectedRowInComponent:] + 76
4   Exercise Generator                  0x000000010d060734 _TFC18Exercise_Generator12selectorView8verticalfP_T_ + 180
5   Exercise Generator                  0x000000010d062713 _TToFC18Exercise_Generator12selectorView8verticalfP_T_ + 67
6   UIKit                               0x000000010db368bc -[UIApplication sendAction:to:from:forEvent:] + 83
7   UIKit                               0x000000010dcbcc38 -[UIControl sendAction:to:forEvent:] + 67
8   UIKit                               0x000000010dcbcf51 -[UIControl _sendActionsForEvents:withEvent:] + 444
9   UIKit                               0x000000010dda60d4 -[UISlider beginTrackingWithTouch:withEvent:] + 1132
10  UIKit                               0x000000010dcbb893 -[UIControl touchesBegan:withEvent:] + 179
11  UIKit                               0x000000010dba4285 -[UIWindow _sendTouchesForEvent:] + 2043
12  UIKit                               0x000000010dba5c33 -[UIWindow sendEvent:] + 4011
13  UIKit                               0x000000010db529ab -[UIApplication sendEvent:] + 371
14  UIKit                               0x000000010e33f72d __dispatchPreprocessedEventFromEventQueue + 3248
15  UIKit                               0x000000010e338463 __handleEventQueue + 4879
16  CoreFoundation                      0x00000001102f7761 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
17  CoreFoundation                      0x00000001102dc98c __CFRunLoopDoSources0 + 556
18  CoreFoundation                      0x00000001102dbe76 __CFRunLoopRun + 918
19  CoreFoundation                      0x00000001102db884 CFRunLoopRunSpecific + 420
20  GraphicsServices                    0x000000011228ca6f GSEventRunModal + 161
21  UIKit                               0x000000010db34c68 UIApplicationMain + 159
22  Exercise Generator                  0x000000010d0674ef main + 111
23  libdyld.dylib                       0x000000011130268d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>```

答:
Take a look at the first few frames of the stack trace. I'll cut out the image and address columns to avoid scrolling:

```<code>'*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'
*** First throw call stack:
(
0   __exceptionPreprocess + 171
1   objc_exception_throw + 48
2   -[__NSArrayM objectAtIndex:] + 203
3   -[UIPickerView selectedRowInComponent:] + 76
4   _TFC18Exercise_Generator12selectorView8verticalfP_T_ + 180
</code>```

We see that your vertical(_:) method asks the picker view for the selected row in a component, and the picker view tries to get an object from an array. The array throws the exception, because it was given index 2, but its valid indexes are only 0 and 1.

The picker view probably has an array of components, and is trying to get component 2 from the array, because (in two different places in vertical(_:)) you ask it about component 2.

My guess is your picker view only has two components, with indexes 0 and 1.

Title: UISlider throwing NSRangeException

Body:
Despite setting each slider's minimum, maximum, and current values to their defaults in the storyboard, moving the slider throws an error saying that the value was somehow moved to 2. In addition, this error only started when I added:

var lElbowX = Int()
var rElbowX = Int()
var lElbowY = Int()
var rElbowY = Int()
var lWristX = Int()
var lWristY = Int()
var rWristX = Int()
var rWristY = Int()
var lKneeX = Int()
var lKneeY = Int()
var rKneeX = Int()
var rKneeY = Int()
var lAnkleX = Int()
var lAnkleY = Int()
var rAnkleX = Int()
var rAnkleY = Int()

and

@IBAction func vertical(_ sender: Any) {//The action function used to be empty
    if jointPicker.selectedRow(inComponent: 2) == 1 {//left
        if jointPicker.selectedRow(inComponent: 1) == 1 {//lNeck
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 2 {//lShoulder
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 3 {//lElbow
            lElbowY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 4 {//lWrist
            lWristY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 5 {//lSpine
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 6 {//lHip
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 7 {//lKnee
            lKneeY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 8 {//lAnkle
            lAnkleY = Int((verticalSlider.value - 0.5) * 200)
        }

    }
    if jointPicker.selectedRow(inComponent: 2) == 2 {//right
        if jointPicker.selectedRow(inComponent: 1) == 1 {//rNeck
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 2 {//rShoulder
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 3 {//rElbow
            rElbowY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 4 {//rWrist
            rWristY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 5 {//rSpine
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 6 {//rHip
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 7 {//rKnee
            rKneeY = Int((verticalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 8 {//rAnkle
            rAnkleY = Int((verticalSlider.value - 0.5) * 200)
        }

    }
}
@IBAction func horizontal(_ sender: Any) {//The action function used to be empty
    if jointPicker.selectedRow(inComponent: 2) == 1 {//left
        if jointPicker.selectedRow(inComponent: 1) == 1 {//lNeck
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 2 {//lShoulder
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 3 {//lElbow
            lElbowX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 4 {//lWrist
            lWristX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 5 {//lSpine
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 6 {//lHip
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 7 {//lKnee
            lKneeX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 8 {//lAnkle
            lAnkleX = Int((horizontalSlider.value - 0.5) * 200)
        }

    }
    if jointPicker.selectedRow(inComponent: 2) == 2 {//right
        if jointPicker.selectedRow(inComponent: 1) == 1 {//rNeck
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 2 {//rShoulder
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 3 {//rElbow
            rElbowX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 4 {//rWrist
            rWristX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 5 {//rSpine
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 6 {//rHip
            //nothing yet
        }
        if jointPicker.selectedRow(inComponent: 1) == 7 {//rKnee
            rKneeX = Int((horizontalSlider.value - 0.5) * 200)
        }
        if jointPicker.selectedRow(inComponent: 1) == 8 {//rAnkle
            rAnkleX = Int((horizontalSlider.value - 0.5) * 200)
        }

    }
}

Call Stack:

2017-07-03 12:38:06.856 Exercise Generator[50942:2970421] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'
*** First throw call stack:
(
0   CoreFoundation                      0x0000000110352d4b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x000000010d66521e objc_exception_throw + 48
2   CoreFoundation                      0x00000001102842eb -[__NSArrayM objectAtIndex:] + 203
3   UIKit                               0x000000010db187ba -[UIPickerView selectedRowInComponent:] + 76
4   Exercise Generator                  0x000000010d060734 _TFC18Exercise_Generator12selectorView8verticalfP_T_ + 180
5   Exercise Generator                  0x000000010d062713 _TToFC18Exercise_Generator12selectorView8verticalfP_T_ + 67
6   UIKit                               0x000000010db368bc -[UIApplication sendAction:to:from:forEvent:] + 83
7   UIKit                               0x000000010dcbcc38 -[UIControl sendAction:to:forEvent:] + 67
8   UIKit                               0x000000010dcbcf51 -[UIControl _sendActionsForEvents:withEvent:] + 444
9   UIKit                               0x000000010dda60d4 -[UISlider beginTrackingWithTouch:withEvent:] + 1132
10  UIKit                               0x000000010dcbb893 -[UIControl touchesBegan:withEvent:] + 179
11  UIKit                               0x000000010dba4285 -[UIWindow _sendTouchesForEvent:] + 2043
12  UIKit                               0x000000010dba5c33 -[UIWindow sendEvent:] + 4011
13  UIKit                               0x000000010db529ab -[UIApplication sendEvent:] + 371
14  UIKit                               0x000000010e33f72d __dispatchPreprocessedEventFromEventQueue + 3248
15  UIKit                               0x000000010e338463 __handleEventQueue + 4879
16  CoreFoundation                      0x00000001102f7761 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
17  CoreFoundation                      0x00000001102dc98c __CFRunLoopDoSources0 + 556
18  CoreFoundation                      0x00000001102dbe76 __CFRunLoopRun + 918
19  CoreFoundation                      0x00000001102db884 CFRunLoopRunSpecific + 420
20  GraphicsServices                    0x000000011228ca6f GSEventRunModal + 161
21  UIKit                               0x000000010db34c68 UIApplicationMain + 159
22  Exercise Generator                  0x000000010d0674ef main + 111
23  libdyld.dylib                       0x000000011130268d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Body:
Take a look at the first few frames of the stack trace. I'll cut out the image and address columns to avoid scrolling:

'*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'
*** First throw call stack:
(
0   __exceptionPreprocess + 171
1   objc_exception_throw + 48
2   -[__NSArrayM objectAtIndex:] + 203
3   -[UIPickerView selectedRowInComponent:] + 76
4   _TFC18Exercise_Generator12selectorView8verticalfP_T_ + 180

We see that your vertical(_:) method asks the picker view for the selected row in a component, and the picker view tries to get an object from an array. The array throws the exception, because it was given index 2, but its valid indexes are only 0 and 1.

The picker view probably has an array of components, and is trying to get component 2 from the array, because (in two different places in vertical(_:)) you ask it about component 2.

My guess is your picker view only has two components, with indexes 0 and 1.


问:
PHP - Rotate image with GD gives black borders
I am trying to rotate and save an image. The rotation is based on the EXIF data. I have tried the following, which all give a black border around it:

Where the original looks like this:

```<code>$orientation = array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($imagePath)['Orientation'] ?: 0];

$source = imagecreatefromjpeg($imagePath);
$resource = imagerotate($source, $orientation, 0);
imagejpeg($resource, $image, 100);
</code>```

I have also tried adding imagealphablending($resource, true); and imagesavealpha($resource, true); as proposed in Black background when rotating image with PHP, but to no avail; the border remains.

Then I tried creating the image with imagecreatetruecolor():

```<code>$imageSizes = getimagesize($image);
$oldWidth  = $imageSizes[0];
$oldHeight = $imageSizes[1];

$orientation = array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($image)['Orientation'] ?: 0];

$source = imagecreatefromjpeg($imagePath);
$resource = imagerotate($source, $orientation, 0);

$newWidth  = $oldWidth;
$newHeight = $oldHeight;

if ($orientation !== 180 && $orientation !== 0) {
    $newWidth  = $oldHeight;
    $newHeight = $oldWidth;
}

$imageResized = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled ($imageResized, $resource, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);
imagejpeg($imageResized, $image, 100);
</code>```

But I just can't seem to get it work. Is anyone able to help me with this?

答:
I've found this problem today in PHP for Windows.  The borders only seem to get added when you do a 0 or 360 degree rotation.  I don't get the borders with a 180 degree rotation.  So, just check to see if orientation is non-zero and only rotate if necessary.

...
if ($orientation !== 0)
  $resource = imagerotate($source, $orientation, 0);
else
  $resource = $source;
end
...

Body:
I am trying to rotate and save an image. The rotation is based on the EXIF data. I have tried the following, which all give a black border around it:

Where the original looks like this:

$orientation = array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($imagePath)['Orientation'] ?: 0];

$source = imagecreatefromjpeg($imagePath);
$resource = imagerotate($source, $orientation, 0);
imagejpeg($resource, $image, 100);

I have also tried adding imagealphablending($resource, true); and imagesavealpha($resource, true); as proposed in Black background when rotating image with PHP, but to no avail; the border remains.

Then I tried creating the image with imagecreatetruecolor():

$imageSizes = getimagesize($image);
$oldWidth  = $imageSizes[0];
$oldHeight = $imageSizes[1];

$orientation = array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($image)['Orientation'] ?: 0];

$source = imagecreatefromjpeg($imagePath);
$resource = imagerotate($source, $orientation, 0);

$newWidth  = $oldWidth;
$newHeight = $oldHeight;

if ($orientation !== 180 && $orientation !== 0) {
    $newWidth  = $oldHeight;
    $newHeight = $oldWidth;
}

$imageResized = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled ($imageResized, $resource, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);
imagejpeg($imageResized, $image, 100);

But I just can't seem to get it work. Is anyone able to help me with this?


问:
Automatically update query in access
I have data in a table and a query to run in access. I want the query to update itself as and when the data is changed in the table. Is it possible to do so in access?

Thank you.

答:
This is not an easy thing to do, but it can be done. My approach would be the following (if you really want to do this):

1 Create a VBA function that opens and closes the query

```<code>Public Function RefreshQuery() As Integer
    DoCmd.Close acQuery, "QueryA"
    DoCmd.OpenQuery "QueryA"
End Function
</code>```

2 Create a data macro on update, change and insert for your relevant table that calls this VBA function by using SetLocalVar to set a local variable equal to it's result

This has numerous disadvantages, such as calling focus to the query every time the table is changed.

I'm not going in to much detail here, because I guess you won't implement this as its use case is limited.

Title: Automatically update query in access

Body:
This is not an easy thing to do, but it can be done. My approach would be the following (if you really want to do this):

1 Create a VBA function that opens and closes the query

Public Function RefreshQuery() As Integer
    DoCmd.Close acQuery, "QueryA"
    DoCmd.OpenQuery "QueryA"
End Function

2 Create a data macro on update, change and insert for your relevant table that calls this VBA function by using SetLocalVar to set a local variable equal to it's result

This has numerous disadvantages, such as calling focus to the query every time the table is changed.

I'm not going in to much detail here, because I guess you won't implement this as its use case is limited.


问:
optimizing Mysql tables with index
```<code>SELECT *
FROM sms_report
WHERE R_uid = '159'
  AND R_show = '1'
ORDER BY R_timestamp DESC , R_numbers
</code>```

This is my query. Now it is using filesort i need to add index so that its optimized.
Below is the output of explain

```<code>id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra

1   SIMPLE  sms_report  ref     R_uid,R_show    R_uid   4   const   765993  Using where; Using filesort
</code>```

The table is MYISAM and i have created indexes on R_smppid, R_uid, R_show, R_timedate, R_numbers

Someone adviced me on adding composite index. can you tell me which all fields should I index and how.

答:
How to add index:

```<code>alter table sms_report add index new_index (uid, show, R_timestamp, R_numbers);
</code>```

How to force query to use new index

```<code>SELECT *
FROM sms_report
USE INDEX new_index
WHERE R_uid=159 AND R_show=1
ORDER BY R_timestamp DESC, R_numbers;
</code>```

Title: optimizing Mysql tables with index

Body:
SELECT *
FROM sms_report
WHERE R_uid = '159'
  AND R_show = '1'
ORDER BY R_timestamp DESC , R_numbers

This is my query. Now it is using filesort i need to add index so that its optimized.
Below is the output of explain

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra

1   SIMPLE  sms_report  ref     R_uid,R_show    R_uid   4   const   765993  Using where; Using filesort

The table is MYISAM and i have created indexes on R_smppid, R_uid, R_show, R_timedate, R_numbers

Someone adviced me on adding composite index. can you tell me which all fields should I index and how.

Body:
How to add index:

alter table sms_report add index new_index (uid, show, R_timestamp, R_numbers);

How to force query to use new index

SELECT *
FROM sms_report
USE INDEX new_index
WHERE R_uid=159 AND R_show=1
ORDER BY R_timestamp DESC, R_numbers;


问:
Using bounds to search for coordinates
I try to create a google maps API call that searches an address in a specific boundary.

So in my test I want to search for "8670" which is a postal code from a village in Belgium. This village:
https://www.google.com/maps/place/8670+Koksijde,+Belgium/@51.1129798,2.6459201,13z/data=!3m1!4b1!4m5!3m4!1s0x47dcba8d702c832d:0x10129f1eb06df0d2!8m2!3d51.117577!4d2.6744402

Using the country-parameter in the API call gives me the right answer:
https://maps.googleapis.com/maps/api/geocode/json?address=8670|country:BE

But using the bounds-parameter returns me a city in the USA:
https://maps.googleapis.com/maps/api/geocode/json?address=8670&bounds=53.6014224,7.0979623|49.4057287,2.4896213

I know bounds is not a strict filter, but as there is a city in range of the bounds with that postal code leaves me with the question why does google not find it and return me a city far away from my bounds?

The reason why I want to use bounds and not country-parameter is because the search is for 3 countries (NL, BE, LU) and as far as I know it is not possible to use OR in the country-parameter.

答:
The documentation says that bounds parameter defines the latitude/longitude coordinates of the southwest and northeast corners of this bounding box.

https://developers.google.com/maps/documentation/geocoding/intro#Viewports

So, the first coordinate should be coordinate of southwest and second coordinate should be coordinate of northeast. In you example you define bounds in opposite order NE|SW. Just swap values in bounds parameter and you will have expected result '8670 Koksijde, Belgium' (place ID ChIJLYMscI263EcR0vBtsB6fEhA):

https://maps.googleapis.com/maps/api/geocode/json?address=8670&bounds=49.4057287%2C2.4896213%7C53.6014224%2C7.0979623&key=YOUR_API_KEY

or

https://maps.googleapis.com/maps/api/geocode/json?components=postal_code%3A8670&bounds=49.4057287%2C2.4896213%7C53.6014224%2C7.0979623&key=YOUR_API_KEY

I hope this helps!

Title: Using bounds to search for coordinates


问:
Dynamic Database table attributes (best practice)
I want to create a DVD Database (MySQL) with custom fields, that means, that the user should be able to add his own information fields to catalogue his DVDs. I just provide the required attributes, for example:

```<code> - ID
 - Title
</code>```

The user can add fields for his own use like

```<code>- Actors
- Year
- Genre
- Plot
- etc
</code>```

Now, what's the best practice for this challenge? I've got some ideas:

Alter the table and add attributes (possible data loss)

Use temporary tables (less performance)

Is there a better idea?

答:
You should try out MySQL 5.7 and its JSON data type.

You can use this to define a semi-structured collection of user-defined attributes.

```<code>CREATE TABLE Dvd (
  id SERIAL PRIMARY KEY,
  title text NOT NULL,
  attr JSON NOT NULL
);

INSERT INTO Dvd
SET title = 'Wonder Woman',
    attr = '{"Actors": ["Gal Godot", "Chris Pine"],
             "Year": "2017",
             "Genre": "Action",
             "Plot": "See Captain America: The First Avenger"
            }';
</code>```

Body:
I want to create a DVD Database (MySQL) with custom fields, that means, that the user should be able to add his own information fields to catalogue his DVDs. I just provide the required attributes, for example:

 - ID
 - Title

The user can add fields for his own use like

- Actors
- Year
- Genre
- Plot
- etc

Now, what's the best practice for this challenge? I've got some ideas:

Alter the table and add attributes (possible data loss)

Use temporary tables (less performance)

Is there a better idea?

Body:
You should try out MySQL 5.7 and its JSON data type.

You can use this to define a semi-structured collection of user-defined attributes.

CREATE TABLE Dvd (
  id SERIAL PRIMARY KEY,
  title text NOT NULL,
  attr JSON NOT NULL
);

INSERT INTO Dvd
SET title = 'Wonder Woman',
    attr = '{"Actors": ["Gal Godot", "Chris Pine"],
             "Year": "2017",
             "Genre": "Action",
             "Plot": "See Captain America: The First Avenger"
            }';


问:
Get the first n/2 of n words in a column in a pandas data frame
I would like to get the first n/2 of n words in a column in a pandas data frame.
Each row can have a different number of words, but every row has an even number of words.
This column contains the name of an item, but every name is duplicated.
For example, One became One One and One Two became One Two One Two.

I thought the following would work.

count the number of words

split the column on spaces

get the first n/2 words in this split

But it doesn't work (I only casually use Python and pandas).
Here is an MWE.

```<code>import pandas as pd
df = pd.DataFrame(['One One', 'One Two One Two'])
df[1] = df[0].str.count('\w+')
df[2] = df[0].str.split()
df[3] = df[0].get(df[2])
</code>```

P.S. Please let me know if you have a good reference on pandas for the R user.

答:
Base on you previous effort :

```<code>df = pd.DataFrame(['One One', 'One Two One Two'])
df[1] = df[0].str.count('\w+')
df[2] = df[0].str.split()
df[3]=df.apply(lambda x: ' '.join(x[2][:int((x[1]/2))]), axis=1)

df
Out[354]:
                 0  1                     2        3
0          One One  2            [One, One]      One
1  One Two One Two  4  [One, Two, One, Two]  One Two
</code>```

My solution(Base on what you mentioned Each row can have a different number of words, but every row has an even number of words. This column contains the name of an item, but every name is duplicated.) :

```<code>df['Target']= df.apply(lambda x: x[0][:int((len(x[0])+1)/2)], axis=1)

df
Out[389]:
                 0    Target
0          One One      One
1  One Two One Two  One Two
</code>```

Body:
I would like to get the first n/2 of n words in a column in a pandas data frame.
Each row can have a different number of words, but every row has an even number of words.
This column contains the name of an item, but every name is duplicated.
For example, One became One One and One Two became One Two One Two.

I thought the following would work.

count the number of words

split the column on spaces

get the first n/2 words in this split

But it doesn't work (I only casually use Python and pandas).
Here is an MWE.

import pandas as pd
df = pd.DataFrame(['One One', 'One Two One Two'])
df[1] = df[0].str.count('\w+')
df[2] = df[0].str.split()
df[3] = df[0].get(df[2])

P.S. Please let me know if you have a good reference on pandas for the R user.

Body:
Base on you previous effort :

df = pd.DataFrame(['One One', 'One Two One Two'])
df[1] = df[0].str.count('\w+')
df[2] = df[0].str.split()
df[3]=df.apply(lambda x: ' '.join(x[2][:int((x[1]/2))]), axis=1)

df
Out[354]:
                 0  1                     2        3
0          One One  2            [One, One]      One
1  One Two One Two  4  [One, Two, One, Two]  One Two

My solution(Base on what you mentioned Each row can have a different number of words, but every row has an even number of words. This column contains the name of an item, but every name is duplicated.) :

df['Target']= df.apply(lambda x: x[0][:int((len(x[0])+1)/2)], axis=1)

df
Out[389]:
                 0    Target
0          One One      One
1  One Two One Two  One Two


问:
libGDX: Box2D velocity not increasing enough
If got a game project where I'm using box2d. Now in my MovementSystem (I'm using a Entity-Component-Based-Approach), I want Box2D to move my objects arround, according to the desired velocities which are set by the controls.

Unfortunately the velocities seems never to get high enough. Even when doing an applyLinearImpulse with a velocity-vector (the desired velocity) of 245044.23 for each axis for example, the resulting velocity of the body just became something about 90.0. What am I'm doing wrong? Is there a limitation or something?

Here's my code for running the velocity-update and world-step:

```<code>//************************
// physics-system
//************************
public void update(float deltaTime) {

        float frameTime = Math.min(deltaTime, 0.25f);
        accumulator += frameTime;
        if (accumulator >= MAX_STEP_TIME) {

            world.step(MAX_STEP_TIME, 6, 2);
            accumulator -= MAX_STEP_TIME;

            for (Entity entity : entities) {
                TransformComponent transform = tim.get(entity);
                BodyComponent bodyComp = bod.get(entity);
                VelocityComponent velocity = vel.get(entity);

                Vector2 bodyVelocity = bodyComp.body.getLinearVelocity();
                float velChangeX = velocity.horizontalVelocity - bodyVelocity.x;
                float velChangeY = velocity.verticalVelocity - bodyVelocity.y;

                float impulseX = bodyComp.body.getMass() * velChangeX;
                float impulseY = bodyComp.body.getMass() * velChangeY;

                bodyComp.body.applyLinearImpulse(new Vector2(impulseX, impulseY), bodyComp.body.getWorldCenter(),
                        false);

                // update transform
                Vector2 position = bodyComp.body.getPosition();
                transform.x = (int) position.x;
                transform.y = (int) position.y;

                // slowingdownVelocitys(velocity);

            }
        }

    }
</code>```

And here the definiton of my currently only entity with a box2D-Component (called a  BodyComponent):

```<code>        Entity entity = new Entity();
        //...
        BodyComponent bodyComponent = new BodyComponent();
        BodyDef bodyDef = new BodyDef();

        bodyDef.type = BodyDef.BodyType.DynamicBody;

        bodyDef.position.set(transformComponent.getX(), transformComponent.getY());

        bodyComponent.body = GameManager.getB2dWorld().createBody(bodyDef);
        bodyComponent.body.applyAngularImpulse(50f, true);

        CircleShape circle = new CircleShape();
        circle.setRadius(2f);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = circle;
        fixtureDef.density = 10f;
        fixtureDef.friction = 0.4f;
        fixtureDef.restitution = 0.6f; // Make it bounce a little bit

        bodyComponent.body.createFixture(fixtureDef);

        circle.dispose();

        entity.add(bodyComponent);
        //...
</code>```

答:
Box2D does limit velocities yes. The limit is there basically to avoid inaccuracies of floating point arithmetic. A velocity of 245044.23 with a step time of 1/60th of a second is well above this limit as you've discovered. If you could lower your step time to say 1/200000th of a second you could simulate 245044.23 meters per second but I think most of us would have trouble getting that to run in real-time. At a step rate of 60 steps per second (each step being only 1/60 of a simulated second), the velocity you've stated is approximately 4084 meters per step since Box2D units are basically MKS units (meters, kilograms, seconds). The velocity limit meanwhile is limited per step to 2 meters per step (by b2_maxTranslation). This limit can be increased but as it's increased you're more likely to see less physical-like behaviors like tunneling.

As to what you're doing wrong, besides trying to use a velocity way higher than Box2D can handle, usually problems like you've described are the result of the visual scaling used. Keep in mind that Box2D positions are in units of meters while most of our monitors are significantly smaller (in either horizontal or vertical direction) than a meter. The Box2D FAQ has this to say about scaling in terms of pixels:

Suppose you have a sprite for a character that is 100x100 pixels. You
  decide to use a scaling factor that is 0.01. This will make the
  character physics box 1m x 1m. So go make a physics box that is 1x1.
  Now suppose the character starts out at pixel coordinate (345,679). So
  position the physics box at (3.45,6.79). Now simulate the physics
  world. Suppose the character physics box moves to (2.31,4.98), so move
  your character sprite to pixel coordinates (231,498). Now the only
  tricky part is choosing a scaling factor. This really depends on your
  game. You should try to get your moving objects in the range 0.1 - 10
  meters, with 1 meter being the sweet spot.

The question that you'll want to answer is what scaling to use such that the physical velocities which Box2D can handle can translate to the visual effect in a way that can still be seen. At the step simulation of 1/60 of second (per step), the limit of velocity that Box2D will deal with is +/- 120 meters per second. But with clever use of scaling between world coordinates and graphical coordinates, that can be like 120 units-of-distance per second where you can sort of make the units-of-distance to be kilometers or tera-meters or whatever.

Beware that going really slow can pose problems too - like running into the velocity threshold for collision responses (b2_velocityThreshold).

Hope this helps!

Body:
If got a game project where I'm using box2d. Now in my MovementSystem (I'm using a Entity-Component-Based-Approach), I want Box2D to move my objects arround, according to the desired velocities which are set by the controls.

Unfortunately the velocities seems never to get high enough. Even when doing an applyLinearImpulse with a velocity-vector (the desired velocity) of 245044.23 for each axis for example, the resulting velocity of the body just became something about 90.0. What am I'm doing wrong? Is there a limitation or something?

Here's my code for running the velocity-update and world-step:

//************************
// physics-system
//************************
public void update(float deltaTime) {

        float frameTime = Math.min(deltaTime, 0.25f);
        accumulator += frameTime;
        if (accumulator >= MAX_STEP_TIME) {

            world.step(MAX_STEP_TIME, 6, 2);
            accumulator -= MAX_STEP_TIME;

            for (Entity entity : entities) {
                TransformComponent transform = tim.get(entity);
                BodyComponent bodyComp = bod.get(entity);
                VelocityComponent velocity = vel.get(entity);

                Vector2 bodyVelocity = bodyComp.body.getLinearVelocity();
                float velChangeX = velocity.horizontalVelocity - bodyVelocity.x;
                float velChangeY = velocity.verticalVelocity - bodyVelocity.y;

                float impulseX = bodyComp.body.getMass() * velChangeX;
                float impulseY = bodyComp.body.getMass() * velChangeY;

                bodyComp.body.applyLinearImpulse(new Vector2(impulseX, impulseY), bodyComp.body.getWorldCenter(),
                        false);

                // update transform
                Vector2 position = bodyComp.body.getPosition();
                transform.x = (int) position.x;
                transform.y = (int) position.y;

                // slowingdownVelocitys(velocity);

            }
        }

    }

And here the definiton of my currently only entity with a box2D-Component (called a  BodyComponent):

        Entity entity = new Entity();
        //...
        BodyComponent bodyComponent = new BodyComponent();
        BodyDef bodyDef = new BodyDef();

        bodyDef.type = BodyDef.BodyType.DynamicBody;

        bodyDef.position.set(transformComponent.getX(), transformComponent.getY());

        bodyComponent.body = GameManager.getB2dWorld().createBody(bodyDef);
        bodyComponent.body.applyAngularImpulse(50f, true);

        CircleShape circle = new CircleShape();
        circle.setRadius(2f);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = circle;
        fixtureDef.density = 10f;
        fixtureDef.friction = 0.4f;
        fixtureDef.restitution = 0.6f; // Make it bounce a little bit

        bodyComponent.body.createFixture(fixtureDef);

        circle.dispose();

        entity.add(bodyComponent);
        //...


问:
Run CGI application without redirecting from HTML
I have an html page populated from a cgi app. Right now when I make a change on my html page through a form

```<code><form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
</code>```

It takes me from

http://localhost/index.html

to

http://localhost/cgi-bin/Lib.exe
where the CGI outputs some debug lines I put in there. I then have to manually go back to the index to see it updated.

When the html form sends a request to the cgi application, the CGi application makes the update to the database and re-writes the index html. How do I stay on the index page and see it updated? (I am running the light weight GoAhead web server, CGI in C, and html,JS)

Thanks.

答:
You can send a 302 status code from the CGI script, which will redirect the user's browser to /index.html.

Basically, make the CGI script spit this out:

```<code>HTTP/1.1 302 Found
Location: /index.html

</code>```

OwnerDisplayName: Tommy

Body:
I have an html page populated from a cgi app. Right now when I make a change on my html page through a form

<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">

It takes me from

http://localhost/index.html

to

http://localhost/cgi-bin/Lib.exe
where the CGI outputs some debug lines I put in there. I then have to manually go back to the index to see it updated.

When the html form sends a request to the cgi application, the CGi application makes the update to the database and re-writes the index html. How do I stay on the index page and see it updated? (I am running the light weight GoAhead web server, CGI in C, and html,JS)

Thanks.

LastEditorDisplayName: Tommy

Body:
You can send a 302 status code from the CGI script, which will redirect the user's browser to /index.html.

Basically, make the CGI script spit this out:

HTTP/1.1 302 Found
Location: /index.html

OwnerDisplayName: strager


问:
What is an efficient method to inject multiple ads into a page using javascript or jquery?
Users can choose to turn on ads. It should display ads if it finds a cookie (or not). I've been able to hack together something that seems to work and do what I need, but it is ugly and clunky. Returning the ad code from a function was the only way I could get it to display correctly. What shortcuts can I use to have only one main function that handles multiple ads?

Please take it easy on me since I'm a beginner. Any suggestions or direction would be great. Thanks.

    var showadsornot = getAdCode();

    // Put strings in array
  var adText = [
    "
Ad Code 1
",
    "
Ad Code 2
",
    "
Ad Code 3
",
    "
Ad Code 4
"
  ];

  // Look in container to get an array of ad elements
  var container = document.getElementById('globalWrapper');
  var ads = container.querySelectorAll('.displayad');

  // For each element insert the string with the same index
  // (i.e. the first string matches the first element, etc.
  Array.from(ads).forEach(function (displayad, index) {
   displayad.innerHTML = writeAdCode(showadsornot, adText[index]);
  });

  function getAdCode() {
   var showadsornot = "1"; // or empty null
   return showadsornot;
  }

  function writeAdCode(showadsornot, adcode) {
   var newAdCodeTwo = "";
   if(showadsornot){
    newAdCodeTwo += adcode;
   } else {
    newAdCodeTwo += "
No Ads For You!
";
   }
   return newAdCodeTwo;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head></head>
<body>
<div id="globalWrapper">

 <!-- Ad Code #1 -->
 <div class="container">
  <div class="displayad"></div>
 </div>

 <!-- Ad Code #2 -->
 <div class="container">
  <div class="displayad"></div>
 </div>

 <!-- Ad Code #3 -->
 <div class="container">
  <div class="displayad"></div>
 </div>

 <!-- Ad Code #4 -->
 <div class="container">
  <div class="displayad"></div>
 </div>

</div>
</body>
</html></code>```

答:
Since you have 4 similar elements and the same number of strings to insert into those elements, using arrays can help.

Say you structure your ad elements in a container like this:

```<code><div id="ad-container">
  <div class="ad"></div>
  <div class="ad"></div>
  <div class="ad"></div>
  <div class="ad"></div>
</div>
</code>```

This would allow you to loop over an array of elements and place the matching text inside of it.

```<code>// First put the strings in an array
var adText = [
  "<ins class='adsbygoogle' style='display:inline-block;width:970px;height:250px' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000001'></ins>",
  "<ins class='adsbygoogle' data-ad-format='auto' style='display:block' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000002'></ins>",
  "<ins class='adsbygoogle' style='display:inline-block;width:970px;height:250px' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000003'></ins>",
  "<ins class='adsbygoogle' style='display:inline-block;width:300px;height:1050px' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000004'></ins>"
];

// Look into the container to get an array of ad elements
var container = document.getElementById('ad-container');
var ads = container.querySelectorAll('.ad');

// For each of these ad elements insert the string with the same index
// (i.e. the first string matches the first element and so on
ads.forEach(function (ad, index) {
  ad.innerHTML = writeAdCode(showadsornot, adText[index]);
});
</code>```

Something else you could do is dynamically add 'ad' elements to an empty container based on the number of ad strings you have in an array. You would simply loop through the array of strings and forEach string create an ad element and insert its text.

Body:
Since you have 4 similar elements and the same number of strings to insert into those elements, using arrays can help.

Say you structure your ad elements in a container like this:

<div id="ad-container">
  <div class="ad"></div>
  <div class="ad"></div>
  <div class="ad"></div>
  <div class="ad"></div>
</div>

This would allow you to loop over an array of elements and place the matching text inside of it.

// First put the strings in an array
var adText = [
  "<ins class='adsbygoogle' style='display:inline-block;width:970px;height:250px' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000001'></ins>",
  "<ins class='adsbygoogle' data-ad-format='auto' style='display:block' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000002'></ins>",
  "<ins class='adsbygoogle' style='display:inline-block;width:970px;height:250px' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000003'></ins>",
  "<ins class='adsbygoogle' style='display:inline-block;width:300px;height:1050px' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000004'></ins>"
];

// Look into the container to get an array of ad elements
var container = document.getElementById('ad-container');
var ads = container.querySelectorAll('.ad');

// For each of these ad elements insert the string with the same index
// (i.e. the first string matches the first element and so on
ads.forEach(function (ad, index) {
  ad.innerHTML = writeAdCode(showadsornot, adText[index]);
});

Something else you could do is dynamically add 'ad' elements to an empty container based on the number of ad strings you have in an array. You would simply loop through the array of strings and forEach string create an ad element and insert its text.


问:
Read last integer file C++
I have a question. Why my program don't read the last integer if I don't put a space at the end of file? If I have a text file with a only number, without end space, the program don't read anything.

This is my program :

```<code>#include <iostream>
#include <fstream>

using namespace std;

int main(){
    fstream f1,f2;
    int k;
    int q;

    cout << "Inserisci numero lettere da leggere : ";
    cin >> q;

    f1.open("in.txt", ios::in);
    f2.open("out.txt", ios::out);

    if(f1.fail()){
        cout << "Impossibile aprire il file";
        exit(1);
    }

    f1 >> k;

    while( !f1.eof() && q > 0){
        q--;
        cout << k << '\n';
        f2 << k;
        f1 >> k;
    }

    f1.close();
    f2.close();

    return 0;
}
</code>```

答:
Your program read all the numbers, but you have !f1.eof() check after a read operation. And when there is an end of file after the last number, you never output it.

Replace

```<code>f1 >> k;

while( !f1.eof() && q > 0){
    q--;
    cout << k << '\n';
    f2 << k;
    f1 >> k;
}
</code>```

with

```<code>while( f1 >> k && q > 0){
    q--;
    cout << k << '\n';
    f2 << k;
}
</code>```

And read some articles about input/output via streams.

Title: Read last integer file C++

Body:
I have a question. Why my program don't read the last integer if I don't put a space at the end of file? If I have a text file with a only number, without end space, the program don't read anything.

This is my program :

#include <iostream>
#include <fstream>

using namespace std;

int main(){
    fstream f1,f2;
    int k;
    int q;

    cout << "Inserisci numero lettere da leggere : ";
    cin >> q;

    f1.open("in.txt", ios::in);
    f2.open("out.txt", ios::out);

    if(f1.fail()){
        cout << "Impossibile aprire il file";
        exit(1);
    }

    f1 >> k;

    while( !f1.eof() && q > 0){
        q--;
        cout << k << '\n';
        f2 << k;
        f1 >> k;
    }

    f1.close();
    f2.close();

    return 0;
}

Body:
Your program read all the numbers, but you have !f1.eof() check after a read operation. And when there is an end of file after the last number, you never output it.

Replace

f1 >> k;

while( !f1.eof() && q > 0){
    q--;
    cout << k << '\n';
    f2 << k;
    f1 >> k;
}

with

while( f1 >> k && q > 0){
    q--;
    cout << k << '\n';
    f2 << k;
}

And read some articles about input/output via streams.